代码之家  ›  专栏  ›  技术社区  ›  Cuckoo

添加暂停以临时禁用单击

  •  1
  • Cuckoo  · 技术社区  · 8 年前

    我正在制作一个简短的脚本来展示我女朋友的礼物,但我不能亲自送。我想在点击之间添加一个暂停,这样她就不会在一秒钟内意外地浏览所有案例。

    var gifty = document.getElementById("gift");
    var counter = 4;
    
    var handler = function() {
      gifty.style.backgroundPosition = counter * 722 + "px " + "0px";
      counter -= 1;
      switch (counter) {
        case 3:
          document.getElementById("head2").innerHTML = "Click it again! Click it again!";
          break;
        case 2:
          document.getElementById("head2").innerHTML = "Hmmm, what could it be?";
          break;
        case 1:
          document.getElementById("head2").innerHTML = "Any ideas what it could be?";
          break;
        case 0:
          document.getElementById("head2").innerHTML = "Surprise! Your new sewing mahcine is waiting for you in Doha! Hope you like it. xxxxx";
          gifty.removeEventListener("click", handler);
          break;
      }
    }
    
    gifty.addEventListener("click", handler);
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   GG.    8 年前

    你可以使用 setTimeout

    const PAUSE_DURATION = 2000 // 2 seconds
    
    const gifty = document.getElementById('gift')
    const header = document.getElementById('head2')
    const setText = text => header.innerHTML = text
    
    let counter = 4
    
    const handler = () => {        
      counter -= 1
      
      switch (counter) {
        case 3: setText('Click it again! Click it again! 😄 '); break
        case 2: setText('Hmmm, what could it be? 🤔 '); break
        case 1: setText('Any ideas what it could be? 😉 '); break
        case 0: setText('Surprise! Your new sewing machine is waiting for you in Doha! Hope you like it. 😘 '); break
      }
      
      removeClickHandler()
      
      setTimeout(() => addClickHandler(), PAUSE_DURATION)
    }
    
    const addClickHandler = () => gifty.addEventListener('click', handler)
    const removeClickHandler = () => gifty.removeEventListener('click', handler)
    
    addClickHandler()
    <div id="gift">
      <h2 id="head2"> Click here! ❤️ </h2>
    </div>
        2
  •  1
  •   Raffael Bechara Rameh    8 年前
    var initialTime = new Date().getTime();
    
    var handler = function() {
        var clickTime = newDate().getTime();
        if (clickTime - initialTime > 1000) { // 1 second
    
             (... do your stuff here ...)
    
           initialTime = new Date().getTime();
        }
    }