当没有发生交互时,jquery隐藏元素

时间:2017-06-01 19:03:07

标签: javascript jquery

我在页面加载时弹出一个元素,它会在5秒后隐藏。我试图创建逻辑,如果用户没有与弹出窗口进行交互,它会隐藏,如果用户确实进行了交互,它会保持显示,如果用户离开元素,计时器再次开始隐藏。

<div id="popup">
  Some popup
  <input type="email" placeholder="enter email" />
</div>

<div id="popup-button" style="display:none;">
  button to open the popup
</div>

// on load, 5 seconds starts
var goTimeout = setTimeout(function(){
  $('#popup').css("display","none");
  $('#popup-button').css("display","block");
  }, 5000);
  goTimeout;


// when mouse enter's popup element and/or user types in input
// should turn off the setTimeout
$(document).on("touchstart click mouseenter keyup", "#popup", function(e){
  e.stopPropagation();
  e.preventDefault();
  console.log(e);
  clearTimeout(goTimeout);
});


// when user mouse leave's the popup the timer starts again, but
// if user is still focused within input field, don't start until
// user clicks outside of the element
$(document).on("mouseleave", "#popup", function(e){
  e.stopPropagation();
  e.preventDefault();
  console.log(e);
  clearTimeout(goTimeout);
  goTimeout;
});

想知道是否有人可以帮助我解决逻辑问题,而不是让我按照我喜欢的方式工作

2 个答案:

答案 0 :(得分:1)

goTimer不是一个函数,但是你试图把它称为像mouseleave部分末尾的函数。创建一个创建/启动计时器的功能,你会很高兴。像这样:

var goTimeout;
function myTimer() {
  goTimeout = setTimeout(function() {
    $('#popup').css("display", "none");
    $('#popup-button').css("display", "block");
    }, 5000);
}
myTimer();

然后只需将mouseleave部分的最后一行更改为:

myTimer();代替goTimeout;

这是一个JSFiddle来检查。

答案 1 :(得分:0)

您可以使用onmouseover,onmousedown等DOM元素。

此外,最后声明的超时似乎是错误,它更多的是变量或计数,而不是函数。

你可以拥有类似的东西,

if #avaliable