如何显示div,如果每5秒按钮没有点击

时间:2017-12-22 22:07:34

标签: javascript

我有一个隐藏的div,我想显示div,但我有一个条件,如果每隔5秒按钮点击,然后div不显示,如果5秒后按钮没有点击,则div显示。

<div style="display: none;">You Fail.</div>
<button type="button" id="proceed">5 seconds click</button>

2 个答案:

答案 0 :(得分:0)

HTML:

<div id="hiddenContent" class="hidden">Some hidden content</div>

<button id="myButton">Click Here</button>

JavaScript的:

(() => {

  const $hidden = document.getElementById('hiddenContent');
  const $myButton = document.getElementById('myButton');
  let intervalId;

  const restartTimer = () => {
    $hidden.classList.add('hidden');
    intervalId = setInterval(() => {
      $hidden.classList.remove('hidden');
    }, 5000)
  };

  const cancelTimer = () => {
    clearInterval(intervalId);
    restartTimer();
  };

  $myButton.addEventListener('click', cancelTimer);
  restartTimer();

})();

工作fiddle

答案 1 :(得分:0)

您可以使用setTimeoutclearTimeout

&#13;
&#13;
let timeout;
document.querySelector('#btn').onclick = (e) => {
  clearTimeout(timeout);
  document.querySelector('#div').style.visibility = "hidden";
  timeout = setTimeout(() => {
    document.querySelector('#div').style.visibility = "visible";
  }, 5000);
};
&#13;
<button id="btn">Click me</button>
<div id="div">Click the button again</div>
&#13;
&#13;
&#13;