swap()
CSS 交换
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
// 得到宽度
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
应用:
JS 获取元素的宽度:$(".div1").get(0).offsetWidth
jQuery 获取元素的宽度:$('.div1').width()
如果元素设置了display:none
那么 JS 就无法获取到元素的宽度。
jQuery
中通过swap
来解决。
原理:删除并保存元素的display:none
样式在 a 变量中,为元素设置display:block; visibility:hidden; position:absolute
。这样的效果和display:none
的效果基本一样,但是能获取到元素的宽度,将宽度保存在变量 b 中。之后使用变量 a 中的样式替换元素当前样式
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
get: function( elem, computed, extra ) {
if ( computed ) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
// Support: Safari 8+
// Table columns in Safari have non-zero offsetWidth & zero
// getBoundingClientRect().width unless display is changed.
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
swap( elem, cssShow, function() {
// 得到元素宽度
return getWidthOrHeight( elem, dimension, extra );
} ) :
getWidthOrHeight( elem, dimension, extra );
}
},
注意:
- 如果元素设置了display:none ,通过原生JS(offsetWidth)获取元素的尺寸,值为0
- jQuery 获取的元素伪数组。加入下标可以直接获取到对应的 DOM 对象,也可以通过 get(index)获取DOM 对象。get 方法支持参数为负数