如何使用纯JavaScript和文档查询选择器实现jquery .on()函数 [英] How to implement jquery .on() function using plain javascript and document query selectors
本文介绍了如何使用纯JavaScript和文档查询选择器实现jquery .on()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
jquery on()函数允许DOM事件在可能插入到其中的元素上触发未来.如何在没有jquery的特定类的元素上使用纯JavaScript特别是mouseenter
事件并使用现代的
jquery on() function allow the DOM event to trigger on an element that may be inserted in the future. How can this be implemented using plain javascript especially a mouseenter
event on elements with a certain class without jquery and using modern document.querySelector
推荐答案
在这里找到了答案 https://developer.mozilla.org/zh-CN/docs/Web/Events/mouseenter
对于任何有兴趣实现代码的人如下:
For anyone interested in implementing code is below:
<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和文档查询选择器实现jquery .on()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文