我最近阅读了有关CSS浏览器功能检测的教程...最终产品就是这样...
var prefix = ['Moz', 'webkit', 'O', 'ms', 'Khtml'],
test_style = document.createElement('div').style;
var css_check = function(prop) {
if (prop in test_style) {
return true;
}
for (var i = 0; i < prefix.length; i++) {
if (prefix[i] + prop in test_style) {
return true;
}
}
return false;
};
css_check('whatev_css_property');
我不明白的部分是...
if (prop in test_style)
或if (foo in bar)
。
根据我阅读的内容,使用if (foo in bar)
来检查一个值是否在数组中,但我可能在这里错了,我没有发现太多的文档。另外,如果用于检查数组中的值,则test_style = document.createElement('div').style
是如何数组?没有意义...
我很困惑。任何澄清都将不胜感激。
语句if (foo in bar)
测试对象bar
是否具有名为 foo
的属性。它不会测试具有值foo
的属性。
是:
var bar = {"a" : "x", "b" : "y"};
alert("a" in bar); // true
alert("x" in bar); // false
您可以在数组上使用此语法,因为它们是一种对象。如果bar
是数组,则foo in bar
如果foo
是具有值的数字索引,或者foo
是其他属性或方法名称。
另外,如果用于检查数组中的值,
test_style = document.createElement('div').style
数组如何?
test_style
是一个对象,而不是数组。
in
操作员用于检查数组或对象中的A 键,例如
3 in [1, 2, 3] // false, since the array indices only go up to 2
2 in [1, 2, 3] // true
'x' in { x: 5 } // true
'toString' in Object.prototype // true
style
属性有一个CSSStyledEclaration的实例,该实例包含Active浏览器中每个受支持的样式属性的属性。
您在帖子中给出的代码段检查是否支持某种版本的样式(官方的浏览器或具有许多普通供应商前缀之一)。
if (foo in bar)
用于检查名为foo
的值是否是对象bar
的属性。由于数组只是经过特殊处理的对象,因此您可以在数组中检查一个值,您是正确的。
test_style = document.createElement('div').style
返回具有属性的对象;由于是这种情况,您可以使用foo in bar
语法对其进行检查。
document.createElement('div').style
将返回具有CSS属性的对象。您可以使用key in
检查对象中是否存在特定属性。