2

我最近阅读了一篇关于 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数组?没有意义...

我很困惑。任何澄清将不胜感激。

4

4 回答 4

3

该语句if (foo in bar)测试对象是否具有名为bar的属性。它不测试具有 value 的属性。 foofoo

那是:

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是一个对象,而不是一个数组。

于 2012-10-31T00:15:37.750 回答
2

in运算符用于检查数组或对象中是否存在键,例如

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的一个实例,它包含活动浏览器中每个支持的样式属性的属性。

您在帖子中提供的代码片段检查查看浏览器是否支持该样式的某个版本(官方版本或具有许多常见供应商前缀之一)。

于 2012-10-31T00:15:51.127 回答
1
 document.createElement('div').style

将返回一个具有 CSS 属性的对象。您可以使用它key in来检查对象中是否存在特定属性。

于 2012-10-31T00:15:26.740 回答
1

if (foo in bar)用于检查命名的值是否foo是对象的属性bar。由于数组只是经过特殊处理的对象,因此假设它可用于检查数组中的值是正确的。

test_style = document.createElement('div').style返回具有属性的对象;既然是这种情况,您可以使用foo in bar语法来检查它。

于 2012-10-31T00:16:15.853 回答