引导警报悬停暂停

时间:2018-07-26 19:17:18

标签: javascript jquery html

如果用户将鼠标悬停在警报上以阅读冗长的消息,我正在寻找一种暂停淡出过程的方法。

window.setTimeout(function() {
    $(".alert").fadeTo(2000, 500).slideUp(500, function(){
    $(".alert").slideUp(500);
    $(this).remove();
    });
}, 4000);


<div id="alert-auto-close" class="alert alert-success alert-dismissible fade show">You have been successfully logged out!
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>

任何想法如何实现?

1 个答案:

答案 0 :(得分:0)

这有点草率,但是从这段代码中,您可以开始更好地格式化它:

var alertBox = $('#alert-auto-close');
var slideOut = function(){
  alertBox.slideUp(500).animate({
    'opacity': 0
  }, {
    'duration': 2000,
    'queue': false,
    'complete': function(){
      $(this).remove();
    }
  });
};
var overAlert = false;
var t = null;

alertBox.on('mouseover', function(){
  $(this).stop(true);
  overAlert = true;
}).find('.close').on('click', function(){
  overAlert = false;
  alertBox.off('mouseover mouseleave');
  slideOut();
});

t = window.setTimeout(function(){
  if(!overAlert) {
    slideOut();
  }
  alertBox.on('mouseleave', slideOut);
}, 4000);

首先,您希望将alert存储在它自己的变量中,以附加事件并捕获鼠标,然后使用slideOut()方法使animation函数通过{ {1}}和queue,您想要一个伪全局变量来使用complete来跟踪鼠标,最后overAlert变量用于保存t,因此我们可以清除它。

现在,有更好的方法来处理此问题,只要找到指针并确定其当前位于setTimeout的范围内即可,但除非元素要移动或与其他叠加层或其他元素分层有吗,在大多数情况下(应该是60/40之类的),应该可以解决这个问题。

alert中,检查标志是否被抛出,如果没有,则开始动画。现在,通常这会破坏默认的setTimeout功能,但是当我们附加close事件时,您会注意到我们还为Close按钮附加了一个处理程序,以确保所有内容都清晰可见并且动画是相同的如果时间用完或按下“关闭”按钮。

以下是一些文档,以帮助您了解我编写此书的原因,并可能激发您进行更多调整(同样,它可以使用改进方法):

jQuery slideUp
jQuery animate
jQuery stop
jQuery fadeTo(第二个参数是不透明度,> = 0 && <= 1)
mouseenter() vs mouseover()

And a jsFiddle just because

相关问题