本篇主要记录一下昨天和同事对JQ里取绝对像素值时对runTimeStyle的一处细节的讨论,同时提出自己的一些疑问。
疑问
最近我的同事 小卡 在整合jquery代码的时候,对JQuery里IE下取精确像素值的部分提出了一些疑问
下面的代码片段来自jquery-1.8.2.js:
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( rnumnonpx.test( ret ) ) {
// Remember the original values
//①
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
//②
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
//③
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
//④
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
主要是代码段②这里
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left; //疑问!
}
疑问:这一句到底是干啥用的?
小卡试过 将这段去掉,在IE6/7/8/9里均不影响最终结果,即使runtimeStyle已经被人为设置过
解释?
我以前看JQ的时候也对DE的这段代码有过疑问,所以我按照那时候的理解给出的解释:
- 当runtimeStyle有值的时候,元素实际渲染总是以此为准,此时:
- 当runtimeStyle的值不存在或者被清空(赋值''就是清空)时,元素的渲染以currentStyle为准。此时:
但 herbert 提出了质疑:
我回过头看了一下上面的代码,发现还真是这么回事。
if ( rsLeft ) {
//进了这个if,说明runtimeStyle.left有值
//当runtimeStyle.left有值时, currentStyle.left的值取出来就是runtimeStyle.left的值
//那下面这句赋值确实无意义啊!囧囧囧~~
elem.runtimeStyle.left = elem.currentStyle.left;
}
为啥我以前研究这里的时候,没发现这个悖论呢?
溯源-反省
去找了下源头:

发现DE原始的代码里并无此判断
然后又翻了一下1.4的JQ,发现里面也是没有这句判断。
发现是1.5版本才增加的这个判断。
那么到底JQ里为啥要增加这句判断呢?
去Github看下history,发现2011年1月5号之前,源码里也是没有这个判断的

可以看到,这里是为了规避opera抛出异常,所以加了一句判断。
到底咋解释?
其中要提的是 element.runtimeStyle 为什么这里也把他临时覆盖了呢? 可能是出于 保险。比如 其他代码中可能更改了此值 因为 runtimeStyle的优先级 要高越style... 所以为了pixelLeft取出正确的值 所以 也覆盖了element.runtimeStyle.
...
相关资料
http://erik.eae.net/archives/2007/07/27/18.54.15/
两篇相关的中文blog:
http://yiminghe.iteye.com/blog/511589
http://www.cnblogs.com/_franky/archive/2009/11/29/1612969.html
runtimeStyle属性的介绍:
http://help.dottoro.com/ljhddfwr.php

被折叠的 条评论
为什么被折叠?



