jQuery源码阅读:swap()

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 方法支持参数为负数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值