如何为多个class为hover的元素绑定hover事件并获取对应DOM属性
解决方案
你完全不需要通过匹配ID的方式实现,直接针对.hover类绑定事件即可,静态/动态新增的元素都可以覆盖,下面分别提供jQuery和原生JS两种实现:
jQuery实现(适配你当前使用的技术栈)
适用场景1:页面加载完成后就存在的.hover元素
// 等DOM加载完成后执行 $(function() { // 绑定hover事件,第一个回调是鼠标进入时触发,第二个是鼠标离开时触发 $('.hover').hover(function() { // 1. 获取当前hover元素的属性 const currentId = $(this).attr('id'); // 取ID const currentText = $(this).text(); // 取文本内容 const currentOffset = $(this).offset(); // 取相对于文档的坐标,currentOffset.top是上侧距离,currentOffset.left是左侧距离 const currentWidth = $(this).width(); // 可选:取元素宽度 const currentHeight = $(this).height(); // 可选:取元素高度 // 2. 调用你的自定义函数,把上面的参数传进去即可 yourCustomFunction(currentId, currentText, currentOffset); }, function() { // 可选:鼠标离开时的逻辑,不需要可以删掉第二个回调 }) })
适用场景2:后续会动态新增的.hover元素(比如AJAX插入的内容)
用事件委托实现,不需要每次新增元素后重新绑定:
$(function() { // 把事件绑定到document(也可以替换成这些.hover元素的固定父级容器,性能更好) $(document).on('mouseenter', '.hover', function() { // 取属性和调用自定义函数的逻辑和上面完全一致 const currentId = $(this).attr('id'); const currentText = $(this).text(); const currentOffset = $(this).offset(); yourCustomFunction(currentId, currentText, currentOffset); }) })
原生JavaScript实现(不需要引入jQuery)
静态元素绑定
// 等DOM加载完成执行 document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('.hover').forEach(el => { el.addEventListener('mouseenter', function() { const currentId = this.id; const currentText = this.textContent; // getBoundingClientRect取相对于视口的坐标,要算文档坐标加滚动偏移即可 const currentRect = this.getBoundingClientRect(); const documentOffsetTop = currentRect.top + window.scrollY; const documentOffsetLeft = currentRect.left + window.scrollX; // 调用自定义函数 yourCustomFunction(currentId, currentText, {top: documentOffsetTop, left: documentOffsetLeft, ...currentRect}); }) }) })
动态元素事件委托
document.addEventListener('mouseenter', function(e) { // 判断触发事件的元素是不是.hover类 if (e.target.classList.contains('hover')) { const el = e.target; const currentId = el.id; const currentText = el.textContent; const currentRect = el.getBoundingClientRect(); const documentOffsetTop = currentRect.top + window.scrollY; const documentOffsetLeft = currentRect.left + window.scrollX; yourCustomFunction(currentId, currentText, {top: documentOffsetTop, left: documentOffsetLeft, ...currentRect}); } }, true)
内容的提问来源于stack exchange,提问作者lioneltour
相关产品推荐
相关产品推荐

