V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
uti6770werty

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

  •  
  •   uti6770werty · Jan 15, 2021 · 2136 views
    This topic created in 1941 days ago, the information mentioned may be changed or developed.
        adiv=document.getElementById('adiv');
        bdiv=document.getElementById('bdiv');
        cdiv=document.getElementById('cdiv');
        // .....
        // ...
        // .
        // 略
        zdiv=document.getElementById('zdiv');
    
        //只对一个元素进行应用
        bdiv.onmousemove = function (activeelement) {
            //xxxx
        }
    

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

    4 replies    2021-01-16 03:58:23 +08:00
    Rhilip
        1
    Rhilip  
       Jan 15, 2021
    这为啥不上个循环?或者如果 id 命名有规律,直接使用 querySelectorAll 来选择
    doucument.querySelectorAll("xxxxx").map(x => x.onmousemove = () => {})
    musi
        2
    musi  
       Jan 15, 2021
    事件委托了解一下?
    shenyuzhi
        3
    shenyuzhi  
       Jan 15, 2021
    在 body 上监听,然后在 target 上 dispatch
    dd112389
        4
    dd112389  
       Jan 16, 2021
    window.addEventListener('mousemove', function (e) {
    // adiv or bdiv or cdiv......
    let target = e.target;
    });
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5603 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 05:52 · PVG 13:52 · LAX 22:52 · JFK 01:52
    ♥ Do have faith in what you're doing.