javascript - 从样式表中读取 CSS 属性

标签 javascript jquery html css

<分区>

我正在尝试像这样访问 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

关于javascript - 从样式表中读取 CSS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16778814/

相关文章:

html - 在 Firefox 中包装单词

javascript - 函数内的 YouTube api 不起作用

javascript - Redux reducer ,将多个api分页请求附加到state

javascript - JQuery 对话框中的大图

javascript - Access-control-allow-origin 无法在 POST 请求中使用 ajax

javascript - 当我用更多 <span> 替换 <font> 标签时,交叉渐变 jQuery 中断

javascript - 避免在 jQuery 悬停时移动 div

javascript - 选择此 LI 项的 jquery 选择器语法是什么

javascript - jQuery:向左滑动和向右滑动

jquery - 即使页面可滚动,也将 div 在屏幕上居中