【问题标题】:Find out if element has a declared value找出元素是否具有声明值
【发布时间】:2014-07-10 02:37:16
【问题描述】:
我想向模块(想想 web 组件)添加一个方法,该方法检测是否已将高度设置为其根元素,如果没有,则根据其他因素计算其高度。
这个模块有一些绝对定位和其他“花哨”的东西,所以正常的流程是不可能的。
我正在考虑遍历document.styleSheets 并检查每个cssRule 的selectorText 中的根元素的id 或类,然后解析cssText 或寻找'height' 的非空键' 在 style 对象中。
有没有更好(或标准)的方法?
PS - 我可能刚刚在提出问题时解决了它,所以如果你遇到同样的问题 - 来吧!
【问题讨论】:
标签:
javascript
css
dom
stylesheet
detection
【解决方案1】:
这是一个相当粗略的实现:
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;
}
可能更健壮,但似乎工作正常。