如果没有点击某个其他div超过x秒,则显示div

时间:2016-02-26 16:36:06

标签: javascript jquery

我目前在javascript中有一个代码,目前我想做的很好:

  • 警告信息首次出现在7秒后
  • 单击或触摸div TARGET时删除警告

但是我没有设法做到这一点:一旦用户点击目标(已经运行),但我希望警报消息重新出现,每次用户未点击.target div超过5秒

我将它改写为更清楚:我希望消息在7秒后首先出现,然后每次用户点击.target时,消息应该消失。但如果他在.target上没有点击超过5秒,则该消息应该重新出现

怎么做?

HTML

<section id="alert-msg" style="visibility: hidden"> 
  <div>my message</div>
</section>

的Javascript

//1. message only appear after 7 sec
function showIt2() {
    document.getElementById("alert-msg").style.visibility = "visible";
  }
  setTimeout(showIt2, 7000); 

// 2. alert message disappear when .target div is clicked
  $('.target').on('click touchstart', function(){
    $("#alert-msg").remove();
  });

这是一个jsfiddle:https://jsfiddle.net/111994re/3/

4 个答案:

答案 0 :(得分:2)

查看此修订版:https://jsfiddle.net/111994re/7/

我已在你的onclick中添加了setTimeout 我已将隐藏的可见性设置为隐藏而不是将其删除(删除它,您可以在此时取消隐藏,您必须重新添加)

//1. message only appear after 7 sec
function showIt2() {
    document.getElementById("alert-msg").style.visibility = "visible";
  }
  setTimeout(showIt2, 7000); 

// 2. alert message disappear when .target div is clicked
  $('.target').on('click touchstart', function(){
    document.getElementById("alert-msg").style.visibility = "hidden";
    setTimeout(showIt2, 5000);
  });

答案 1 :(得分:1)

好的,现在,警告在x秒后出现。然后,如果用户点击目标,计时器将重置,并在无限期x秒后再次显示警报。

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>

<section id="alert-msg"> 
    <div style="display:none;">Alert!</div>
</section>

<div class="target">Target</div>

<script type="text/javascript">
//1. message only appear after 7 sec
function showIt2() {
    if( $('#alert-msg') ){
        $('#alert-msg div').fadeOut();
        $('#alert-msg div').fadeIn();
    }
  }
  var show = setInterval(showIt2, 5000); 

// 2. alert message disappear when .target div is clicked
  $('.target').on('click touchstart', function(){
    $("#alert-msg div").hide();
    clearInterval(show);
    show = setInterval(showIt2, 5000); 
  });
</script>

答案 2 :(得分:1)

有哪些输入错误

//1. message only appear after 7 sec
function showIt2() {
    document.getElementById("alert-msg").style.visibility = "visible";
  }
  setTimeout(showIt2, 7000); 

// 2. alert message disappear when .target div is clicked
  $('.target').on('click touchstart', function(){
    $("#alert-msg").remove();
});
<section id="alert-msg" style="visibility: hidden"> 
  <div>my message</div>
</section>

答案 3 :(得分:1)

https://jsfiddle.net/111994re/10/

   //1. message only appear after 7 sec
function showIt2() {
    $("#alert-msg").show();
  }
  setTimeout(showIt2, 7000); 

// 2. alert message disappear when .target div is clicked
  $('.target').on('mousedown touchstart', function(){
  $("#alert-msg").hide(); 
    clearTimeout(this.downTimer);

  }).on("mouseup touchstop", function(e) {
    this.downTimer = setTimeout(function() {

          showIt2();
    }, 5000);
});