延迟函数执行JS

时间:2018-04-12 15:34:56

标签: javascript

我想在mouseenterclick事件中显示和隐藏两个div之间切换。但是,如果click事件发生在与mouseenter区域相同的位置,则函数进入循环,如下面的gif所示。

enter image description here

如何延迟showOverlay函数几秒钟,但保持mouseenter事件正常工作,如下面的gif(即无延迟):

enter image description here

任何帮助将不胜感激?



var hover = document.querySelector('#hover');
var overlay = document.querySelector('#overlay');
var primary = document.querySelector('#primary');
var overlayShowing = false;
var clicked = false

function showOverlay() {
  overlayShowing = true
    overlay.classList.add('display');
    setTimeout(function(){ 
      overlay.classList.add('active');
    }, 100);
    primary.classList.add('nactive');
}

function hideOverlay() {
  overlayShowing = false
  overlay.classList.remove('active');

  primary.classList.remove('hidden');
  setTimeout(function(){
    primary.classList.remove('nactive');
  }, 100); 
}

primary.addEventListener('transitionend', function() {
  if(overlayShowing) {
     primary.classList.add('hidden');
   }
 })

overlay.addEventListener('transitionend', function() {
  if(!overlayShowing) {
  overlay.classList.remove('display');
  }
  
});

hover.addEventListener('mouseenter', function(event) {
  showOverlay();
});

overlay.addEventListener("click", function() {
  hideOverlay();
});

#primary {
  opacity: 1;
  display: block;
  transition: 0.5s ease
}
#primary.hidden {
  display: none !important;
}
#primary.nactive {
  opacity: 0;
}
#hover {
  font-size: 150px;
}
#overlay {
  position: fixed;
  height: 100vh;
  width: 100vw;
  top: 0;
  left: 0;
  background-color: black;
  opacity: 0;
  display: none;
  transition: 0.5s ease
}
#overlay.active {
  opacity: 0.8;
}
#overlay.display {
  display: block;
}

<div id="primary">
  <div id="hover">HOVER</div>
</div>
<div id="overlay"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

只需使用超时延迟显示:

  var showTimeout;

  function showOverlay() {
   if(showTimeout) return;

   showTimeout = setTimeout(() => {
     overlayShowing = true;
     overlay.classList.add('display');
     setTimeout(function(){ 
       overlay.classList.add('active');
      }, 100);
      primary.classList.add('nactive');
  }, 500);
 }

 function hideOverlay() {
   if(showTimeout) {
     clearTimeout(showTimeout);
     showTimeout = null;
   }

   overlayShowing = false
   overlay.classList.remove('active');

   primary.classList.remove('hidden');
   setTimeout(function(){
     primary.classList.remove('nactive');
   }, 100); 
}