如何使用纯 Javascript 和文档查询选择器实现 jQuery .on() 函数
How to implement jQuery .on() function using plain Javascript and document query selectors
jquery on() 函数允许 DOM 事件在将来可能插入的元素上触发。如何使用纯Javascript来实现这一点,特别是在没有jQuery的具有特定类的元素上的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>
相关文章:
- 如何从ASP.NET并将其发送到jQuery?(实现FullCalendar)
- 如何使用ajax和JQuery实现Dependent下拉zend框架1.12表单
- jQuery-实现唯一的连续排名
- 如何使用jQuery实现导航栏
- 尝试使用 JChartFX 和 JQUERY 实现图表
- 如何使用jquery实现垂直图像滑块,其中在显示新图像之前,它将关闭并使用新图像打开
- 有没有像tungle.me这样的日历调度程序的javascript/jquery实现
- 通过jQuery实现图像无限循环
- 通过数据属性和jquery实现可重用
- 如何使用javascript/jquery实现用户输入的生活风格
- 'Ctrl+B'使用inputtype=按钮通过jQuery实现功能
- 当特定框悬停时,如何将jQuery实现到类的特定类
- 如何用Javascript、jQuery实现CORS
- 使用HTML/CSS/JQuery实现一个所见即所得的报表生成器
- jquery实现的请等待对话框- safari特有的问题
- 在jQuery中添加一个简单的Java 'class'表示jQuery实现的实例
- 如何用jquery实现这一点
- 如何使用jQuery实现“夜间模式”没有在每个页面加载时闪烁的白色
- 使用JavaScript或jquery实现箭头键
- safari中日期[dd/mm/yyyy]无效?如何使用jquery实现日/月/年格式的显示