我正在尝试像这样访问 css 属性:
.box {
position: absolute;
background-color: red;
height: 10px;
width: 10px;
}
JS:
var height = $('.box').css('height');
我知道,上面的代码是错误的,这实际上不起作用,因为 .box
在 DOM 中不可用。
我尝试的另一件事:
var height = $("<span class='box'></span>").css('height');
我的问题是:如何在 DOM 中没有类 box
的任何元素的情况下获取 .box
的高度?
在现代浏览器上,您可以使用 document.stylesheets , 并且样式表需要在原始 HTML 中并且源需要匹配 Same Origin Policy ,即你不能从 Chrome 扩展中注入(inject)样式表,因为它没有显示在 document.stylesheets
CSS
.box {
position:absolute;
background-color:red;
height:10px;
width:10px;
}
Javascript
function propertyFromStylesheet(selector, attribute) {
var value;
[].some.call(document.styleSheets, function (sheet) {
return [].some.call(sheet.rules, function (rule) {
if (selector === rule.selectorText) {
return [].some.call(rule.style, function (style) {
if (attribute === style) {
value = rule.style.getPropertyValue(attribute);
return true;
}
return false;
});
}
return false;
});
});
return value;
}
console.log(propertyFromStylesheet(".box", "height"));
输出
10px
关于 jsfiddle