悬停JavaScript超过3秒

问题描述 投票:0回答:1

我正在尝试编写普通的javascript,如果img悬停在javascript上,它将监听,如果图像悬停3秒钟,则会打开一个新标签页。目前我正在做这样的事情

 img.addEventListener('mouseover', changeDefOver);
img.setAttribute( 'class', 'myCssClass' );
function changeDefOver(e) {
  window.open("https://www.geeksforgeeks.org", "_blank");
}

但是这将立即执行,并且不会检查3秒钟。我也不能使用jQuery。有什么想法吗?

javascript
1个回答
1
投票

因此,请使用超时,如果用户离开该元素,则删除该超时。

function over() {
  this.timeout = window.setTimeout(function () {
    console.log('here')
  }, 3000)
}

function left() {
  if (this.timeout) window.clearTimeout(this.timeout)
}

img.addEventListener('mouseenter', over);
img.addEventListener('mouseleave', left);

0
投票

弹出窗口阻止程序可能会阻止此操作,但是您可以使用setTimeout.

let hoverTimeout;

function changeDefOver(e) {
  hoverTimeout = setTimeout(() => {
     window.open("https://www.geeksforgeeks.org", "_blank");
  }, 3000);
}

function clearHoverTimeout() {
   clearTimeout(hoverTimeout);
}

但是您还需要清理超时:

img.addEventListener('mouseout', clearHoverTimeout);
© www.soinside.com 2019 - 2024. All rights reserved.