文字覆盖-一定时间后

时间:2019-01-02 00:42:57

标签: javascript html css

我想删除按钮。访客停止点击页面上的鼠标30秒钟后,代码会自动激活

function on() {
  document.getElementById("overlay").style.display = "block";
}

function off() {
  document.getElementById("overlay").style.display = "none";
}
#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.7);
  z-index: 2;
  cursor: pointer;
}

#text{
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 50px;
  color: white;
  transform: translate(-50%,-50%);
  -ms-transform: translate(-50%,-50%);
}
<div id="overlay" onclick="off()">
  <div id="text">Where  you gone?</div>
</div>


  <button onclick="on()">I want to remove this button and make the icon activate automatically after a specified time</button>
</div>

我想删除按钮。访客停止点击页面上的鼠标30秒钟后,代码会自动激活

1 个答案:

答案 0 :(得分:0)

使用setTimeoutclearTimeout

使用4000 ms的示例:

var EL_overlay = document.getElementById("overlay");
var timeoutOverlay = null;

function on() {
  EL_overlay.style.display = "block";
}

function off() {
  EL_overlay.style.display = "none";
  clearTimeout(timeoutOverlay);          // Clear existing timeout
  timeoutOverlay = setTimeout(on, 4000); // and start a new one
}

// Keep clicking to reset ongoing timeout.
// If you stop clicking, a notification will appear after 4 sec
document.body.addEventListener('click', off); 
off(); // Start the first timeout....
html, body {height: 100%;}

#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.7);
  z-index: 2;
  cursor: pointer;
}
#text{
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 50px;
  color: white;
  transform: translate(-50%,-50%);
  -ms-transform: translate(-50%,-50%);
}
<div id="overlay">
  <div id="text">Where  you gone?</div>
</div>

不要忘记添加html, body {height: 100%;}