悬停时冻结通知并继续鼠标离开

时间:2018-06-14 06:15:32

标签: jquery notifications setinterval

我正在尝试在我的网站上创建假随机通知。我希望通知以8.5到15秒的范围内的随机时间间隔出现,如果没有立即使用X按钮关闭而没有悬停,则会在4秒内消失。在悬停时我想停止(清除)此间隔并在其中起作用。我的代码似乎没有错误,但它不起作用。出现通知,但X按钮和悬停停止不起作用。我有两种代码变体,两种都不起作用:

 var notify = $("#notify");
 var notification;
 var rand = Math.round(Math.random() * (15000 - 8500)) + 8500;

 notify.mouseenter(function() {
  if (notification) { clearInterval(notification) }
 })
 .mouseleave(function() {
     notification = setInterval(function() {
      $.get("http://mywebsite.com/ajaxurl", function(data) {
        notify.fadeIn().html(data).delay(4000).fadeOut('slow');
        var noticlose = $('.noticlose');
        noticlose.click(function() {
          notify.fadeOut('slow')
        });
      });
      }, rand);
 }).mouseleave();

第二

var notify = $("#notify");
var notification;
var rand = Math.round(Math.random() * (15000 - 8500)) + 8500;

notification = function() {
      $.get("http://mywebsite.com/ajaxurl", function(data) {
        notify.fadeIn().html(data).delay(4000).fadeOut('slow');
        var noticlose = $('.noticlose');
        noticlose.click(function() {
          notify.fadeOut('slow')
        });
      });  
}

var interval = setInterval(notification , rand);

notify.hover(function (ev) {
    clearInterval(interval);
}, function (ev) {
    interval = setInterval(notification , rand);
});

1 个答案:

答案 0 :(得分:0)

你做错了两件事,因此它不起作用。

首先click事件绑定到区间函数内的.noticlose,您不应该这样做。所以只需要这个

var noticlose = $('.noticlose');
noticlose.click(function() {
  notify.fadeOut('slow')
});

notification函数之外。

其次您停止mouseenter上的间隔,并在mouseleave上再次设置,并且它可以正常运行。但是通知会隐藏,因为区间中的函数会显示并隐藏它。因此,即使您停止间隔,先前触发的功能也会隐藏通知。我希望你能理解我所说的话。

因此,要解决此问题,您可以在#notify上使用.stop()功能,以便它不会隐藏。

这是一个工作示例(我删除了ajax以使其工作,但它应该是相同的)



var notify = $("#notify");
var notification;
var rand = Math.round(Math.random() * (15000 - 8500)) + 8500;

var noticlose = $('.noticlose');
noticlose.click(function() {
  notify.fadeOut('slow')
});

notification = function() {
  notify.fadeIn().delay(4000).fadeOut('slow');
}

var interval = setInterval(notification, rand);

notify.on('mouseenter', function(ev) {
  clearInterval(interval);
  notify.stop(true, true);
}).on('mouseleave', function(ev) {
  interval = setInterval(notification, rand);
  notify.delay(4000).fadeOut('slow');
});

#notify {
  padding: 10px 15px;
  box-shadow: 0 0 6px #CCC;
  display: inline-block;
}

#notify .noticlose {
  cursor: pointer;
  margin-left: 5px;
  padding: 0 10px;
  display: inline-block;
  height: 20px;
  line-height: 15px;
}

#notify .noticlose:hover {
  box-shadow: 0 0 12px #CCC;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notify">Notify content <span class="noticlose">x</span></div>
&#13;
&#13;
&#13;

相关问题