详解原⽣js实现offset⽅法
在为 jTool 提供 offset (获取当前节点位置)⽅法时,先后使⽤了两种⽅式进⾏实现,现整理出来以作记录。
前后共使⽤了两种⽅式实现了该⽅法,这⾥将这两种⽅法分别列出。
通过递归实现
function offset(element) {
var offest = {
top: 0,
left: 0
};
var _position;
getOffset(element, true);
return offest;
// 递归获取 offset, 可以考虑使⽤ getBoundingClientRect
function getOffset(node, init) {
// ⾮Element 终⽌递归
if (deType !== 1) {
return;
}
_position = ComputedStyle(node)['position'];
// position=static: 继续递归⽗节点
if (typeof(init) === 'undefined' && _position === 'static') {
getOffset(node.parentNode);
nodeselector
return;
}
offest.left = node.offsetLeft + offest.left - node.scrollLeft;
// position = fixed: 获取值后退出递归
if (_position === 'fixed') {
return;
}
getOffset(node.parentNode);
}
}
/
/ 执⾏offset
var s_kw_wrap = document.querySelector('#s_kw_wrap');
offset(s_kw_wrap); // => Object {top: 181, left: 400}
通过ClientRect实现
function offset2(node) {
var offest = {
top: 0,
left: 0
};
// 当前为IE11以下, 直接返回{top: 0, left: 0}
if (!ClientRects().length) {
return offest;
}
// 当前DOM节点的 display === 'node' 时, 直接返回{top: 0, left: 0}
if (ComputedStyle(node)['display'] === 'none') {
return offest;
}
// BoundingClientRect()⽅法返回元素的⼤⼩及其相对于视⼝的位置。
// 返回值包含了⼀组⽤于描述边框的只读属性——left、top、right和bottom,单位为像素。除了 width 和 height 外的属性都是相对于视⼝的左上⾓位置⽽⾔的。 // 返回如{top: 8, right: 1432, bottom: 548, left: 8, width: 1424…}
offest = BoundingClientRect();
var docElement = node.ownerDocument.documentElement;
return {
top: p + window.pageYOffset - docElement.clientTop,
left: offest.left + window.pageXOffset - docElement.clientLeft
};
}
// 执⾏offset
var s_kw_wrap = document.querySelector('#s_kw_wrap');
offset2(s_kw_wrap); // => Object {top: 181.296875, left: 399.5}
offset2() 函数中使⽤到了 .getClientRects() 与 .getBoundingClientRect() ⽅法,IE11 以下浏览器并不⽀持; 所以该种实现,只适于现代浏览器。
.getClientRects()
返回值是 ClientRect 对象集合(与该元素相关的CSS边框),每个 ClientRect 对象包含⼀组描述该边框的只读属性——left、top、right 和 bottom,单位为像素,这些属性值是相对于视⼝的top-left的。
并包含 length 属性, IE11以下可以通过是否包含 length 来验证当前是否为IE11以上版现。
.getBoundingClientRect()
返回值包含了⼀组⽤于描述边框的只读属性——left、top、right 和 bottom,单位为像素。除了 width 和 height 外的属性都是相对于视⼝的左上⾓位置⽽⾔的。
.getBoundingClientRect() 与 .getClientRects()的关系
1. 这两个⽅法的区别与当前的 display 相关,当 display=inline 时, .getClientRects() 返回当前节点内每⼀⾏⽂本的
ClientRect 对象数组,此时数组长度等于⽂本⾏数。
2. 当 display != inline 时, .getClientRects() 返回当前节点的 ClientRect 对象数组,此时数组长度为1.
3. .getBoundingClientRect() 总是返回当前节点的 ClientRect 对象,注意这⾥是 ClientRect 对象⽽不是对象数组。
提⽰
以上测试,可以通过在百度⾸页执⾏进⾏测试, document.querySelect('#s_kw_wrap') 所获取到的节点为百度⾸页输⼊框
希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论