aCa*_*lla 5 javascript jquery delay settimeout font-awesome
我在我正在处理的网页上有字体真棒刷新图标.
<i class="fa fa-refresh fa-3x" id="lock-refresh"></i>
Run Code Online (Sandbox Code Playgroud)
单击此图标时,我希望它开始旋转.我已经能够通过在我的JavaScript文件中输入以下内容来完成此任务:
$( '#lock-refresh' ).click(function() {
$( this ).addClass( 'fa-spin' ).
//Below is a function that I need to run after the FA icon is clicked.
startup();
});
Run Code Online (Sandbox Code Playgroud)
不过,我只需要这个图标旋转几秒钟.我试图将这个(下面)添加到我的JS文件中,但是当我这样做时,图标根本不会旋转:
$( '#lock-refresh' ).click(function() {
$( this ).addClass( 'fa-spin' );
//Trying to remove the class after 1000 milliseconds. Not working.
$( this ).delay(1000).removeClass( 'fa-spin' );
startup();
});
Run Code Online (Sandbox Code Playgroud)
我也试过以下,但效果不好:
$( '#lock-refresh' ).click(function() {
$( this ).addClass( 'fa-spin' ).delay(1000).removeClass( 'fa-spin' );
startup();
});
Run Code Online (Sandbox Code Playgroud)
我也试过以下,但是当我这样做时,图标开始旋转但不会停止:
$( '#lock-refresh' ).click(function() {
$( this ).addClass( 'fa-spin' );
//Trying to use setTimeout, but doesn't seem to work either.
setTimeout(function() { $( this ).removeClass( 'fa-spin' ); }, 1000);
startup();
});
Run Code Online (Sandbox Code Playgroud)
我已经尝试了以上所有没有我的startup()
功能,它产生了相同的结果,所以我确定它不是功能.
如何让我的FA刷新图标旋转一两秒,然后停止?
delay
在这种情况下,您不能使用方法,因为addClass不返回队列接口以使用延迟.
所以你应该使用setTimeout
但this
在内部使用正确的值.问题是setTimeout将在全局object(this === window
)上下文中执行回调函数.所以你需要提供一个适当的上下文.为此,使用Function.prototype.bind方法很方便:
$( '#lock-refresh' ).click(function() {
$( this ).addClass( 'fa-spin' );
setTimeout(function() {
$( this ).removeClass( 'fa-spin' );
}.bind(this), 1000);
startup();
});
Run Code Online (Sandbox Code Playgroud)
你应该做:
$( '#lock-refresh' ).click(function() {
$( this ).addClass( 'fa-spin' );
var $el = $(this);
setTimeout(function() { $el.removeClass( 'fa-spin' ); }, 1000);
startup();
// Whatever here.
});
Run Code Online (Sandbox Code Playgroud)
因为this
里面有别的东西setTimeout(function(){
,并没有指向被点击的元素.
查询的CSS操作没有排队,但您可以通过执行以下操作使其在'fx'队列中执行:
$( '#lock-refresh' ).click(function() {
$(this).addClass("fa-spin").delay(1000).queue('fx', function() { $(this).removeClass('fa-spin'); });
startup();
// Whatever here.
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3224 次 |
最近记录: |