gpt4 book ai didi

javascript - 如何使用纯 Javascript 和文档查询选择器实现 jQuery .on() 函数

转载 作者:可可西里 更新时间:2023-11-01 13:50:23 27 4
gpt4 key购买 nike

jquery on() function允许 DOM 事件在将来可能插入的元素上触发。如何在没有 jQuery 的情况下使用普通 Javascript 尤其是 mouseenter 事件在具有特定类的元素上实现并使用现代 document.querySelector .

最佳答案

在这里找到答案 https://developer.mozilla.org/en-US/docs/Web/Events/mouseenter

对于任何有兴趣实现代码的人如下:

<ul id="test">
<li>
<ul class="enter-sensitive">
<li>item 1-1</li>
<li>item 1-2</li>
</ul>
</li>
<li>
<ul class="enter-sensitive">
<li>item 2-1</li>
<li>item 2-2</li>
</ul>
</li>
</ul>

<script>
var delegationSelector = ".enter-sensitive";

document.getElementById("test").addEventListener("mouseover", function( event ) {
var target = event.target,
related = event.relatedTarget,
match;

// search for a parent node matching the delegation selector
while ( target && target != document && !( match = matches( target, delegationSelector ) ) ) {
target = target.parentNode;
}

// exit if no matching node has been found
if ( !match ) { return; }

// loop through the parent of the related target to make sure that it's not a child of the target
while ( related && related != target && related != document ) {
related = related.parentNode;
}

// exit if this is the case
if ( related == target ) { return; }

// the "delegated mouseenter" handler can now be executed
// change the color of the text
target.style.color = "orange";
// reset the color after a small amount of time
setTimeout(function() {
target.style.color = "";
}, 500);


}, false);


// function used to check if a DOM element matches a given selector
// the following code can be replaced by this IE8 compatible function: https://gist.github.com/2851541
function matches( elem, selector ){
// the matchesSelector is prefixed in most (if not all) browsers
return elem.matchesSelector( selector );
};
</script>

关于javascript - 如何使用纯 Javascript 和文档查询选择器实现 jQuery .on() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35561655/

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