【发布时间】:2015-12-26 00:55:18
【问题描述】:
我在 java 脚本中有一段动态代码,用于分析页面上的样式表。我的大部分部件都在工作,但我有一个挂断......
我正在检查某些样式表是否存在的部分。 MDN 对此有这样的说法,“[StyleSheetList] 是一个类似数组的对象,但不能使用 Array 方法进行迭代。但是它可以......转换为一个数组。”它们包括一个将对象转换为规则数组的示例,但我看不到获取路径的明确方法。它还说“styleSheetList[index]”是一种可以访问它的方式。我尝试创建这个函数,但它不起作用,总是返回 false...
function checkStyleSheet (styleSheetPath){
var mysheets=document.styleSheets;
for (var i = 0, max = mysheets.length; i < max; i++) {
if (mysheets[i].href == styleSheetPath){
return true;
}
}
return false;
}
谢谢
JFiddle https://jsfiddle.net/3jsvbwrv/
编辑: for 循环中 mysheets[i] 的 console.log 返回...
// CSSStyleSheet → http://example.com/example.css
CSSStyleSheet {
ownerRule: null,
cssRules: CSSRuleList[1],
type: "text/css",
href: null,
ownerNode: <style>,
parentStyleSheet: null,
title: "",
media: Object[0],
disabled: false
}
编辑 2: 注意:在 if 语句中将 mysheets[i].href 更改为 mysheets[i] 并不能解决问题。 example.css 仍然会被认为是 false。
编辑 3: 我不觉得它应该有任何影响,但以防万一它可能有用,或者提供更广泛的概述,或者帮助上下文......那里的 CSS 脚本是通过首先调用的这个函数包含的(经验证可以工作)...
function addStyleSheet (styleSheetPath){
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = styleSheetPath;
document.getElementsByTagName("head")[0].appendChild(link);
}
我的最终目标是完成这项工作......
function requireStyleSheet (styleSheetPath){
if (!checkStyleSheet(styleSheetPath)){
addStyleSheet(styleSheetPath);
}
}
编辑 4 我的测试html:
<button onmousedown="addStyleSheet('htt://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css')">Step1</button>
<button onmousedown="requireStyleSheet('http://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css')">Step 2</button>
编辑 5 正如一些测试人员指出的那样,代码按原样运行。事实证明,我的问题是调用的文件在我的第二个函数尝试检查其存在之前尚未完成加载。
【问题讨论】:
-
请追踪/记录 mysheets[i]
-
谢谢.. href 在这里为空,所以 mysheets[i].href == styleSheetPath 将不起作用,除非 styleSheetPath 也为空...
-
刚刚在这里测试过它可以工作,href 有一个值。请告诉我您声明 的 html
-
还测试了您的 addStyleSheet 函数,这里一切正常...
-
现在请做一个小提琴,这在 cmets 中太难阅读了
标签: javascript arrays dom stylesheet