找出元素是否有声明的值

Find out if element has a declared value

本文关键字:声明 是否 元素      更新时间:2023-09-26

我想添加一个方法到一个模块(认为web组件),检测高度是否已设置为其根元素,如果没有-计算其高度基于其他因素

这个模块有一些绝对的定位和其他"花哨"的东西,所以正常的流动是不可能的。

我正在考虑通过document.styleSheets循环并检查每个cssRuleselectorText中根元素的id或类,然后解析cssText或寻找style对象内的"高度"的非空键。

是否有更好的(或标准的)方法来做这件事?

PS -我可能刚刚解决了它,而制定的问题,所以如果你遇到同样的问题-这里你去!

这是一个非常粗糙的实现:

isHeightSet: function () {
    var id = this.elements.root.id,
        _isHeightSet = false; // the crude part ;-)
    // go through stylesheets
    _.each(document.styleSheets, function(styleSheet) {
        // go through rules
        _.each(styleSheet.cssRules, function(cssRule) {
            // if selectorText contains our id
            if (cssRule.selectorText && cssRule.selectorText.indexOf(id) !== -1) {
                // check if the height is set
                if (cssRule.style.height && 
                   (cssRule.style.height !== 'auto' && 
                    cssRule.style.height !== 'inherit')) {
                    // keep on hacking!
                    _isHeightSet = true;
                }
            }
        });
    });
    return _isHeightSet;
}

可能更健壮,但似乎工作得很好。