代码之家  ›  专栏  ›  技术社区  ›  Ado Ren

当用户单击鼠标时,从mouseover捕获所有事件目标,然后停止

  •  0
  • Ado Ren  · 技术社区  · 8 年前

    我想把所有的都录下来 event.target

    document.addEventListener('click', function() {
      document.addEventListener('mouseover', record);
      document.addEventListener('mouseup', removeListener);
    })
    
    function record(e) {
      console.log(e.target);
    }
    
    function removeListener() {
      document.removeEventListener('mouseover', record);
      document.removeEventListener('mouseup', removeListener);
    }
    <div class='toto'>Toto</div>
    <div class='toto'>Toto</div>
    <div class='toto'>Toto</div>
    <div class='toto'>Toto</div>

    addEventListener('click') 在mouseup上触发,因此顺序如下:

    document.addEventListener('click', function() {
        //Following would start once mouseup
        document.addEventListener('mouseover', record);
        //Following never triggers cause mouse is already up
        document.addEventListener('mouseup', removeListener);
    })
    

    the answer 是要替换 'click' 具有 'mousedown'

    document.addEventListener('mousedown', function() {
      document.addEventListener('mouseover', record);
      document.addEventListener('mouseup', removeListener);
    })
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   Lazar Nikolic    8 年前

    我用叉子叉了你的密码笔,你可以看到结果: https://codepen.io/Lazzaro83/pen/EeoxEW

    document.addEventListener('mousedown', function() {
      document.addEventListener('mouseover', record);
    document.addEventListener('mouseup', removeListener);
    }) 
    
        2
  •  1
  •   XaelGa    8 年前

    你的问题是因为你把一个监听器放在另一个监听器里面,这不是一个可靠的方法,因为就执行的ms而言,记住JS不是“顺序的”,不要担心,让三个监听器活下去,一个更好的方法是做一个全局变量,它像一个开关一样工作:

      let switch = false;
    
       document.addEventListener('click', function(e) {
       e.stopPropagation(); 
       switch = true;
       }); 
       document.addEventListener('mouseover', function(e){
       e.stopPropagation();
        if (switch){
        console.log(e.target);
        }
       });
       document.addEventListener('mouseup', function(e){
       e.stopPropagation();
       switch = false;
       }) ;
    

    https://codepen.io/LeonAGA/pen/eyWpMV

    当做!