{x:expression(...)}做什么?

Sta*_*low 4 javascript expression

我遇到querySelectorAll了IE7的这个polyfill :

https://gist.github.com/connrs/2724353

我以为我在JavaScript中是Okayish,但我从来没有见过像polyfill第9行中的引用部分:

{x:expression(document.__qsaels.push(this))}
Run Code Online (Sandbox Code Playgroud)

显然,它是一个具有键x和价值的JavaScript对象expression(document.__qsaels.push(this)),但除此之外,我知道,这对我来说是神秘的.这个expression功能有什么作用?我无法通过谷歌找到任何东西.

Bol*_*ock 11

您正在查看生成的CSS规则.这不是JavaScript对象,而是CSS声明块.

这条线

styleTag.styleSheet.cssText = selector + "{x:expression(document.__qsaels.push(this))}";
Run Code Online (Sandbox Code Playgroud)

将CSS选择器与声明块连接成一串CSS.声明块包含一个名为CSS的虚拟CSS属性x,其值为expression(document.__qsaels.push(this)).

什么expression() 旧版IE的非标准功能,它允许作者直接执行任意JavaScript并获取在CSS中使用的值.因此,虽然整个字符串是CSS声明块,但document.__qsaels.push(this)实际上是一个JavaScript表达式.

这个表达式的作用是将匹配CSS选择器的任何元素推送到__qsaels数组中,以便polyfill可以将它作为选择器匹配的元素集返回.1从本质上讲,这就是填料的工作原理.

作为一个具体示例,调用polyfilled document.querySelectorAll(".foo")会导致IE7将以下CSS附加到文档样式表:

.foo{x:expression(document.__qsaels.push(this))}
Run Code Online (Sandbox Code Playgroud)

有一些缩进和换行符所以它类似于传统的CSS:

.foo {
  x: expression(document.__qsaels.push(this))
}
Run Code Online (Sandbox Code Playgroud)

在这里,您可以看到此CSS规则将应用于任何匹配的元素.foo,从而导致__qsaels在返回之前添加每个元素.


1 无论出于何种原因,IE似乎都乐于expression()在未知属性上执行语句(AFAIK x甚至在IE7上也没有这样的属性,但我知道什么?).