gpt4 book ai didi

javascript - document.body.style 是什么奇怪的对象

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:12 24 4
gpt4 key购买 nike

document.body.style(or element.style) 是 CSSStyleDeclaration 的一个实例,我想用这个属性来检查浏览器是否支持一些指定的 css 属性

像这样

if("border-width" in document.body.style){
//do sth. if supported
}

但是:

我发现了一件奇怪的事

document.body.style["border-width"] //""
document.body.style.hasOwnProperty("border-width") //true
"border-width" in document.body.style //true

//iterating from Object
for( var i in document.body.style){
if( i == "border-width" ){
console.log("found it")
}
}

但上次无法记录“found it”,这意味着我们在迭代中没有找到“border-width”。

为什么?

即使 document.body.style[1111] 返回 ""但不是 undefined ,1111 也是一个属性吗?

好奇怪好困惑。

最佳答案

如果你想测试一个属性是否可用,使用typeof。例如

var out = document.getElementById('out');

['background', 'backgroundColor', 'background-color', 'backgroundColour',
'-moz-border-radius', '-webkit-border-radius'].forEach(function(prop) {
var li = document.createElement('li');
li.innerHTML = '<code>' + prop + '</code> is ' + (typeof out.style[prop] === 'undefined' ? '<strong>not</strong> ' : '') + 'available';
out.appendChild(li);
});
<ul id="out"></ul>

关于javascript - document.body.style 是什么奇怪的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33162220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com