jquery源码12 offset() : 位置和尺寸的方法
// Back Compat <1.8 extension point
jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {//设置
return options === undefined ?
this :
this.each(function( i ) {//每一个元素设置
jQuery.offset.setOffset( this, options, i );
});
}
//获取
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;//document if ( !doc ) {
return;
} docElem = doc.documentElement;//html标签 // Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
} // getBoundingClientRect()得到一些属性值:ClientRect {top: 8, right: 58, bottom: 58, left: 8, width: 50…},是到可视区的不包含滚动区域,
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );//获取window
//pageYOffset是y轴的滚动距离,clientTop边框宽度,
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
}; jQuery.offset = {
//设置offset
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),//获取元素的position属性,
curElem = jQuery( elem ),
props = {}; // Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {//没有定位就加一个相对定位
elem.style.position = "relative";
} curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left; } else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
} if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
} if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
} if ( "using" in options ) {
options.using.call( elem, props ); } else {
curElem.css( props );
}
}
}; jQuery.fn.extend({ position: function() {//获取
if ( !this[ 0 ] ) {
return;
} var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect(); } else {
// 原生方法找父级
offsetParent = this.offsetParent(); // Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
} // Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
} // 自己的top减去父级的top
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
}, offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
} return offsetParent || docElem;
});
}
}); // Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem ); if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
} if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
); } else {
elem[ method ] = val;//原生的方法
}
}, method, val, arguments.length, null );
};
}); function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) {
var doc;
//是window就得到可视区的宽高
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
} //是document就得到页面的宽高
if ( elem.nodeType === 9 ) {
doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
} return value === undefined ?
jQuery.css( elem, type, extra ) ://css方式获取 jQuery.style( elem, type, value, extra );//style方式获取
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() { // The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
}; jQuery.fn.andSelf = jQuery.fn.addBack; // })();
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
} // If there is a window object, that at least has a document property,
// define jQuery and $ identifiers
if ( typeof window === "object" && typeof window.document === "object" ) {
window.jQuery = window.$ = jQuery;
} })( window );
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>sss</title>
<script src="jquery-203.js"></script>
</head>
<body>
<script>
window.onload = function(){ console.log( $('#div1').offset().left );//到屏幕左边的距离。不看父节点有没有定位 console.log( $('#div2').position().left );//到屏幕左边的距离。相对于有定位的父级,不计算margin值 $('#div2').position( {left:100,top:100} );//会自动加一个相对定位 console.log($('#div2').get(0).getBoundingClientRect());//ClientRect {top: 8, right: 58, bottom: 58, left: 8, width: 50…},是到可视区的不包含滚动区域, }
</script>
</head> <body> <div id="div1" style="width:100px;height:100px;background-color:yellow;posotion:relative;">
<div id='div2' style="width:50px;height:50px;background-color:red;position:left;left:10;top:10" > </div>
</div>
</body>
</html>
jquery源码12 offset() : 位置和尺寸的方法的更多相关文章
- jQuery 源码分析(十六) 事件系统模块 底层方法 详解
jQuery事件系统并没有将事件监听函数直接绑定到DOM元素上,而是基于数据缓存模块来管理监听函数的,事件模块代码有点多,我把它分为了三个部分:分底层方法.实例方法和便捷方法.ready事件来讲,好理 ...
- jQuery源码笔记(一):jQuery的整体结构
jQuery 是一个非常优秀的 JS 库,与 Prototype,YUI,Mootools 等众多的 Js 类库相比,它剑走偏锋,从 web 开发的实用角度出发,抛除了其它 Lib 中一些中看但不实用 ...
- jQuery源码解析资源便签
最近开始解读jQuery源码,下面的链接都是搜过来的,当然妙味课堂 有相关的一系列视频,长达100多期,就像一只蜗牛慢慢爬, 至少品读三个框架,以后可以打打怪,自己造造轮子. 完全理解jQuery源代 ...
- jQuery源码逐行分析学习01(jQuery的框架结构简化)
最近在学习jQuery源码,在此,特别做一个分享,把所涉及的内容都记录下来,其中有不妥之处还望大家指出,我会及时改正.望各位大神不吝赐教!同时,这也是我的第一篇前端技术博客,对博客编写还不是很熟悉,美 ...
- jQuery源码逐行分析学习02(第一部分:jQuery的一些变量和函数)
第一次尝试使用Office Word,方便程度大大超过网页在线编辑,不过初次使用,一些内容不甚熟悉,望各位大神见谅~ 在上次的文章中,把整个jQuery的结构进行了梳理,得到了整个jQuery的简化结 ...
- jquery源码 整体架构
一.对外提供接口 对外提供了jQuery. //可以通过jQuery或者$来找到jQuery (function(window,undefined){ //(21,94) 定义了一些变量和函数 jQu ...
- jquery源码分析(二)——架构设计
要学习一个库首先的理清它整体架构: 1.jQuery源码大致架构如下:(基于 jQuery 1.11 版本,共计8829行源码)(21,94) 定义了一些变量和函数jQu ...
- jquery源码学习(一)——jquery结构概述以及如何合适的暴露全局变量
jQuery 源码学习是对js的能力提升很有帮助的一个方法,废话不说,我们来开始学习啦 我们学习的源码是jquery-2.0.3已经不支持IE6,7,8了,因为可以少学很多hack和兼容的方法. jq ...
- jQuery源码分析笔记
jquery-2.0.3.js版本源码分析 (function(){ (21,94) 定义了一些变量和函数 jQuery = function(){}; (96,283) 给JQ对象,添加一些方法 ...
随机推荐
- mysql if使用实例
//DELIMITER DROP PROCEDURE if EXISTS createAmountCount; create PROCEDURE createAmountCount() BEGIN D ...
- Spring深入浅出(二)IOC的单例 ,继承,依赖,JDBC,工厂模式以及自动装载
IOC的单例模式--Bean Spring中的bean是根据scope来决定的. scope有4种类型: 1.singleton:单例模型,表示通过Spring容器获取的该对象是唯一的.常用并且默认. ...
- Ubuntu18.06 Mate桌面环境下VirtuslBox打开虚拟机“全局菜单”异常退出解决办法
在安装完Ubuntu18.06 Mate桌面环境后在VirtuslBox里打开虚拟机会出现“全局菜单”异常退出问题. 产生上面问题的原因是你的虚拟机可能在 显示= >屏幕= >硬件加速里勾 ...
- P3157 [CQOI2011]动态逆序对 CDQ分治
一道CDQ分治模板题简单来说,这道题是三维数点对于离线的二维数点,我们再熟悉不过:利用坐标的单调递增性,先按更坐标排序,再按纵坐标排序更新和查询时都直接调用纵坐标.实际上,我们是通过排序将二维中的一维 ...
- 冒泡排序php
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <b ...
- windows平台Perl模块离线安装
工具: Perl windows工具:ActivePerl-5.24.0.2400-MSWin32-x86-64int-300560.exe Dmake工具:https://cpan.metacpan ...
- 紫书 例题 10-27 UVa 10214(欧拉函数)
只看一个象限简化问题,最后答案乘4+4 象限里面枚举x, 在当前这条固定的平行于y轴的直线中 分成长度为x的一段段.符合题目要求的点gcd(x,y) = 1 那么第一段1<= y <= x ...
- JS几种遍历方式比较
几种遍历方式比较 for of 循环不仅支持数组.大多数伪数组对象,也支持字符串遍历,此外还支持 Map 和 Set 对象遍历. for in 循环可以遍历字符串.对象.数组,不能遍历 Set/Map ...
- LiquiBase预判断
预判断解决的问题:运行liquibase之前,DB中已经存在一个table,所以需要加上预判断: 完整的一个例子: <?xml version="1.0" encoding= ...
- cocos2d-x 3.1 学习(一):工具安装与配置环境
初级学习cocos2d-x 3.1开发,学习开发过程记录到博客上面来,哪写的不正确请指点. 1.工具安装 cocos2d-x 3.1rc0 最新版本号,下载后解压.下载地址:http://www.co ...