我使用下面的代码在 10 秒内淡出 #widget,并在 10.2 秒内淡入 #floating_widget。这工作得很好。
但是,当我单击或将鼠标悬停在 #widget 容器上时,#widget 容器不应淡出。现在,由于 setTimeout 代码,它会自动淡出。
请告诉我如何解决这个问题?谢谢
HTML:
<div id="widget">
<h1>Hello World!</h1>
</div>
<div id="floating_widget">
<h2>Hello World 2!</h2>
</div>
JS:
setTimeout(function() {
$('#widget').fadeOut('slow');
}, 10000);
setTimeout(function() {
$('#floating_widget').fadeIn('slow');
}, 10200);
$('#floating_widget').click(function(){
$(this).hide();
$('#widget').show();
});
最佳答案
我希望我对你的问题有正确的理解。您似乎遇到了超时问题。您必须在 onmouseover
函数中清除它们。下面是 JavaScript 的示例:
var $widget = $('#widget')
var $floatingWidget = $('#floating_widget')
var widgetFadeTimeout = setTimeout(function() {
$widget.fadeOut('slow')
}, 10000)
var floatingWidgetFadeTimeout = setTimeout(function() {
$floatingWidget.fadeIn('slow')
}, 10200)
$widget.mouseover(function() { // https://api.jquery.com/mouseover
// Remove the timeout to avoid triggering the fadeOut and fadeIn
clearTimeout(widgetFadeTimeout) // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout
clearTimeout(floatingWidgetFadeTimeout)
// In case the element began the transitions stop them
$widget.stop()
$floatingWidget.stop()
$floatingWidget.hide()
$widget.show()
})
$floatingWidget.click(function() {
$(this).hide()
$widget.show()
})
希望这对您有用!
关于javascript - 当鼠标悬停或单击 div 上的事件时阻止淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41733362/