首页 > 解决方案 > 引导警报悬停暂停

问题描述

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

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>

知道如何实现吗?

标签: javascriptjqueryhtml

解决方案


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

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()使用该方法创建函数以使用andanimation进行更多控制,您希望使用伪全局来跟踪鼠标,最后是变量是为了让我们可以清除它。queuecompleteoverAlerttsetTimeout

现在,有更好的方法来处理这个问题,只要定位指针并确定它当前在边界内,alert但除非元素要移动或者它与其他覆盖层或你有什么分层,这应该处理它大多数情况下(嗯,比如 60/40)。

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

这里有一些文档可以帮助你理解我写这篇文章的原因,并可能会激励你对其进行更多调整(同样,它可以使用改进):

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

一个 jsFiddle 只是因为


推荐阅读