根据“批量对象元素集合”,去应用脚本的 onmousemove 动作,如何实现?

2021-01-15 17:06:58 +08:00
 uti6770werty
    adiv=document.getElementById('adiv');
    bdiv=document.getElementById('bdiv');
    cdiv=document.getElementById('cdiv');
    // .....
    // ...
    // .
    // 略
    zdiv=document.getElementById('zdiv');

    //只对一个元素进行应用
    bdiv.onmousemove = function (activeelement) {
        //xxxx
    }

是不是只能对每个 div 元素重复地写 onmousemove 函数?
有优雅的批量写法吗?

1353 次点击
所在节点    JavaScript
4 条回复
Rhilip
2021-01-15 17:49:52 +08:00
这为啥不上个循环?或者如果 id 命名有规律,直接使用 querySelectorAll 来选择
doucument.querySelectorAll("xxxxx").map(x => x.onmousemove = () => {})
musi
2021-01-15 19:09:06 +08:00
事件委托了解一下?
shenyuzhi
2021-01-15 20:41:21 +08:00
在 body 上监听,然后在 target 上 dispatch
dd112389
2021-01-16 03:58:23 +08:00
window.addEventListener('mousemove', function (e) {
// adiv or bdiv or cdiv......
let target = e.target;
});

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/745305

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX