下面是一个 jQuery 语句,它div
在它的点击事件中隐藏了一个元素。我希望元素淡出,无论它是否在 5 秒后没有被点击。有没有一种简单的方法可以fadeOut
在同一个表达式中调用函数,或者click
事件不会干扰动画?
$(".fadeOutbox").click(function(){
$(this).fadeOut('slow');
});
下面是一个 jQuery 语句,它div
在它的点击事件中隐藏了一个元素。我希望元素淡出,无论它是否在 5 秒后没有被点击。有没有一种简单的方法可以fadeOut
在同一个表达式中调用函数,或者click
事件不会干扰动画?
$(".fadeOutbox").click(function(){
$(this).fadeOut('slow');
});
大多数 jQuery 组件都是可链式的,您的函数会返回对初始对象的引用。
您只需使用以下方法即可实现您想要的:
$(".fadeOutbox").click(function () {
$(this).stop().fadeOut('slow');
}).delay(5000).fadeOut('slow');
基本上读作 onclick,淡出,否则 5 秒后淡出。
我假设这是在另一个显示框的函数中。此解决方案将在 5 秒后或单击后立即隐藏该框。
var $box = $('.fadeOutbox');
var fadeOut = function() {
clearTimeout(timeout);
$box.fadeOut('slow');
};
var timeout = setTimeout(fadeOut, 5000);
$box.click(fadeOut);
编辑以澄清:
var clear = setTimeout(function(){ $(".fadeOutbox").fadeOut('slow'); }, 5000);
$(".fadeOutbox").on('click', function(){
clearTimeout(clear);
});
演示:http: //jsfiddle.net/mGbHq/
使用不在点击处理程序内部的超时:
setTimeout(function () {
$(".fadeOutbox").fadeOut('slow');
}, 5000);
您的 jQuery 代码变为:
// set a timeout for 5 seconds
setTimeout(function () {
$(".fadeOutbox").fadeOut('slow');
}, 5000);
// attach click handler
$(".fadeOutbox").on("click", function () {
$(this).fadeOut('slow');
});
保存用户是否点击的事实并在计时器中进行测试
var isClicked = false;
setTimeout(function () {
if(!isClicked)
$(".fadeOutbox").fadeOut('slow');
}, 5000);
$(".fadeOutbox").click(function () {
isClicked = true;
});
试试这个:
var wasClicked = false;
$(".fadeOutbox").click(function () { wasClicked = true; });
setTimeout(function () {
if(wasClicked = false)
$(".fadeOutbox").fadeOut('slow');
}, 5000);
尝试为超时保留一个变量,并在每次用户单击时清除它。
// Timeout variable
var t;
$('.fadeOutBox').click(function()
{
$box = $(this);
$box.fadeIn("fast");
// Reset the timeout
clearTimeout(t);
t = setTimeout(function()
{
$box.fadeOut("slow");
}, 5000);
});
希望这对您有所帮助。
哇,没有一个答案给出了简单的解决方案:使用setTimeout
并取消点击超时:
$(".fadeOutbox").click(function () {
// Cache the jQuery object
var $this = $(this);
// Do we already have a timer running?
var timer = $this.data("timer");
if (timer) {
// Yes, cancel it
clearTimeout(timer);
$this.removeData("timer");
}
// (You may want an `else` here, it's not clear)
// In five seconds, fade out
$this.data("timer", setTimeout(function() {
$this.removeData("timer");
$this.fadeOut('slow');
}, 5000));
});
我不能 100% 确定以上是否触发了您想要的事件,但是两个相关代码是这样的,它们安排了定时操作:
// In five seconds, fade out
$this.data("timer", setTimeout(function() {
$this.removeData("timer");
$this.fadeOut('slow');
}, 5000));
而这会取消它(例如,在点击时):
var timer = $this.data("timer");
if (timer) {
// Yes, cancel it
clearTimeout(timer);
$this.removeData("timer");
}