原文地址: Effect Delay Trick
作者: Karl
PS: E文不好,看这文章简单,就试着翻译下。:)
注:需要jQuery框架。
这是一个没有使用setTimeout而快速实现延迟效果的Trick.
例如,每当用户点击按钮的时候,我都希望在页面显示一个警告信息.但我不希望这个警告信息永远显示在页面上,我希望他几秒钟后自动消失.
好,先让我们来看看实现效果,点击下面的按钮看看
当这个信息显示的时候希望你喜欢!
HTML
好,首先我们需要一条信息,它拥有一个单独的容器:
<div class="quick-alert">警告,欢迎来到luluStudio!</div>
哦,我们也要把我们的Button放到HTML中,就像这样:
<input type="button" id="show-alert" value="Show Alert" />
CSS
现在我也可能需要为"quick-alert"定义
一个样式:










我会把这个放到我的StyleSheet中,所以它将会被应用到我们新的、由按钮产生的DIV中。
插入内容
进入代码!首先,当有人点击“显示警告”按钮的时候我们的警告信息将会被插入。让我们把警告信息放到按钮的右边,就像:
$('#show-alert').click(function() {
$('<div class="quick-alert">Alert! Watch me before it\'s too late!</div>')
.insertAfter( $(this) );
});
});
那么,基本上,我所说的是,点击<input id="show-alert" />按钮,会产生包含该class的DIV和所有的文本在其中,并将产生的DIV放到按钮的右边。主意"it\'s"其中的反斜杠。这是必须的单引号转义符,因为否则"JavaScript会把它解析为字符串的结束符号"(原文:Notice the backslash in "it\'s." That keeps jQuery from getting confused That escapes the single quote, which is necessary because otherwise — as Dave Cardwell explains in his comment — "the JavaScript parser would interpret that as the close of the string." )
添加效果
到目前为止一切顺利。现在我将会去添加我的 .fadeIn()
和 .fadeOut()
效果。在这个完成之后,我会移除我刚才创建的DIV。没必要将它保留:
$('#show-alert').click(function() {
$('<div class="quick-alert">Alert! Watch me before it\'s too late!</div>')
.insertAfter( $(this) )
.fadeIn('slow')
.fadeOut('slow', function() {
$(this).remove();
});
});
});
因为我将 $(this).remove()
放在.fadeOut()方法的回调(callback)中,它会在
.fadeOut()
方法完成后执行。
延迟
题目说这是一个Trick,对不?好的,我希望这不是一个肮脏的Trick(dirty trick),但这里会有完整的代码:
$('#show-alert').click(function() {
$('<div class="quick-alert">Alert! Watch me before it\'s too late!</div>')
.insertAfter( $(this) )
.fadeIn('slow')
.animate({opacity: 1.0}, 3000)
.fadeOut('slow', function() {
$(this).remove();
});
});
});
你看到.animate()
放在那里了吗?这使它完全不透明3秒钟,但这个DIV已经是不透明的了,因此它只是坐在那里就好像它3秒钟什么都没做。难道那样不可爱吗?