How to count clicks with javascript?

后端 未结 8 2236
予麋鹿
予麋鹿 2020-12-01 22:14

Can I count clicks on links with javascript?

8条回答
  •  不思量自难忘°
    2020-12-01 23:00

    Here's a simple click counter with a limiting factor of 200ms between clicks. In this example I've made it so after 3 subsequent clicks something will happen:

    var onClick = (function(){
      var count = 0, timer;
      return function(){
        count++;
        clearTimeout(timer);
        timer = setTimeout(function(){count = 0}, 200);
        // do whatever after 3 clicks
        if( count > 2 )
          document.body.classList.toggle('mode');
      }
    })();
    
    document.body.addEventListener("click", onClick);
    html, body{ height:100%; }
    
    body{ 
      font:20px Arial; 
      text-align:center; 
      padding:20px; 
      background:#EFDCE8;
      transition:.3s;
      -moz-user-select:none;
      -webkit-user-select:none;
    }
    
    body.mode{ background:lightgreen; }
    
    
    
      
    
    
        Click anwhere 3 times
    
    

提交回复
热议问题