gpt4 book ai didi

javascript - 如何使用普通 JavaScript 获取这些 jQuery 结果?

转载 作者:行者123 更新时间:2023-12-01 01:58:34 24 4
gpt4 key购买 nike

有人知道如何在没有 JavaScript 库的情况下获得 jQuery 的 .offset().closest() 的等效项吗?

对于 .closest(),如果我知道要爬上 DOM 树多远,我就可以使用那么多 .parentNode,但如果我不知道'不知道要走多远,我被困住了。

最佳答案

jQuery 的核心是 javascript。您可以使用这个jQuery source viewer找出任何方法的实现。

例如,以下是closest的实现方式:

closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];

if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
level = 1;

if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];

if ( !matches[selector] ) {
matches[selector] = jQuery.expr.match.POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}

while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[selector];

if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}

cur = cur.parentNode;
level++;
}
}

return ret;
}

var pos = POS.test( selectors ) ?
jQuery( selectors, context || this.context ) : null;

for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];

while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;

} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context ) {
break;
}
}
}
}

ret = ret.length > 1 ? jQuery.unique(ret) : ret;

return this.pushStack( ret, "closest", selectors );
}

这是偏移的实现:

jQuery.fn.offset = function( options ) {
var elem = this[0], box;

if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}

if ( !elem || !elem.ownerDocument ) {
return null;
}

if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}

try {
box = elem.getBoundingClientRect();
} catch(e) {}

var doc = elem.ownerDocument,
docElem = doc.documentElement;

// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box || { top: 0, left: 0 };
}

var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ),
scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;

return { top: top, left: left };
};

关于javascript - 如何使用普通 JavaScript 获取这些 jQuery 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4689701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com