原生js實現offset方法

2021-09-24 08:10:48 字數 2375 閱讀 7868

在為 jtool 提供 offset (獲取當前節點位置)方法時, 先後使用了兩種方式進行實現, 現整理出來以作記錄。

function offset(element) ;

var _position;

getoffset(element, true);

return offest;

// 遞迴獲取 offset, 可以考慮使用 getboundingclientrect

function getoffset(node, init)

_position = window.getcomputedstyle(node)['position'];

// position=static: 繼續遞迴父節點

if (typeof(init) === 'undefined' && _position === 'static')

offest.top = node.offsettop + offest.top - node.scrolltop;

offest.left = node.offsetleft + offest.left - node.scrollleft;

// position = fixed: 獲取值後退出遞迴

if (_position === 'fixed')

getoffset(node.parentnode); }}

// 執行offset

var s_kw_wrap = document.queryselector('#s_kw_wrap');

offset(s_kw_wrap); // => object

複製**

function offset2(node) ;

// 當前為ie11以下, 直接返回

if (!node.getclientrects().length)

// 當前dom節點的 display === 'node' 時, 直接返回

if (window.getcomputedstyle(node)['display'] === 'none')

// element.getboundingclientrect()方法返回元素的大小及其相對於視口的位置。

// 返回值包含了一組用於描述邊框的唯讀屬性——left、top、right和bottom,單位為畫素。除了 width 和 height 外的屬性都是相對於視口的左上角位置而言的。

// 返回如

offest = node.getboundingclientrect();

var docelement = node.ownerdocument.documentelement;

return ;

}// 執行offset

var s_kw_wrap = document.queryselector('#s_kw_wrap');

offset2(s_kw_wrap); // => object

複製**

offset2()函式中使用到了.getclientrects().getboundingclientrect()方法,ie11 以下瀏覽器並不支援; 所以該種實現, 只適於現代瀏覽器。

返回值是 clientrect 物件集合(與該元素相關的css邊框),每個 clientrect 物件包含一組描述該邊框的唯讀屬性——left、top、right 和 bottom,單位為畫素,這些屬性值是相對於視口的top-left的。

幷包含 length 屬性, ie11以下可以通過是否包含 length 來驗證當前是否為ie11以上版現。

返回值包含了一組用於描述邊框的唯讀屬性——left、top、right 和 bottom,單位為畫素。除了 width 和 height 外的屬性都是相對於視口的左上角位置而言的。

.getboundingclientrect() 與 .getclientrects()的關係 這兩個方法的區別與當前的 display 相關, 當 display=inline 時, .getclientrects() 返回當前節點內每一行文字的 clientrect 物件陣列, 此時陣列長度等於文字行數。

當 display != inline 時, .getclientrects() 返回當前節點的 clientrect 物件陣列,此時陣列長度為1.

.getboundingclientrect() 總是返回當前節點的 clientrect 物件, 注意這裡是 clientrect 物件而不是物件陣列。

getclientrects

getboundingclientrect

以上**是在進行jtool類庫編碼時實踐出來的方式,歡迎star

用js實現offset方法

工作忙 準備面試,好久沒有更新了。有點時間就想休息一下。不能再墮落下去了,拖著疲憊的身體咬咬牙更新兩篇。本來前段時間在整理關於vue元件封裝 bind實現 promise實現的文章。但是由於篇幅有點大,並且筆記有些久遠好多東西還要再更新下,所以就推遲了。就簡單整理下最近自己寫過的 中比較有代表性的例...

原生JS實現bind方法

bind方法建立乙個新函式。呼叫新函式時,this指向給定的物件,並且將給定的引數列表作為原函式的引數序列的前若干項。當使用new操作符建立bind函式的例項時,bind函式變成構造器,給定的物件引數失效,其餘引數仍然有效。function mybind function fn 臨時函式protot...

原生js實現Ajax方法

一般來說,大家可能都會習慣用jquery提供的ajax方法,但是用原生的js怎麼去實現ajax方法呢?原生js實現ajax let ajax xhr.send data應為 a a1 b b1 這種字串格式,在jq裡如果data為物件會自動將物件轉換成這種字串格式 post function url...