[英]Execute jquery animate only one time
I've the following function: 我有以下功能:
$('.link1').click(function(){
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
});
It toggles a div and scroll the page down. 它切换div并向下滚动页面。 The problem is that everytime the user toggles the page scroll down again...how could I run this animate function only at first click?
问题是,每次用户切换页面再次向下滚动时...我怎么能只在第一次点击时运行这个动画功能?
Use a flag or set a data attribute to make sure the scrolling animation only occurs on the first click. 使用标志或设置数据属性以确保滚动动画仅在第一次单击时发生。
var flag=true;
$('.link1').click(function(){
$("#div2").slideUp(function(){$("#div1").slideToggle();});
if (flag) {
$('html, body').animate({scrollTop: '600px'}, 800);
flag = false;
}
});
I'm guessing #div2
should still toggle, but that it just should'nt scroll on every click? 我猜
#div2
应该仍然切换,但它不应该在每次点击时滚动?
jQuery .one() http://api.jquery.com/one/ jQuery .one() http://api.jquery.com/one/
$('.link1').one( 'click', function(){
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
});
use the .one
function to bind an event that fires only once. 使用
.one
函数绑定仅触发一次的事件。
$('.link1').one('click', function(){
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
});
The following works with JQuery. 以下适用于JQuery。
The CSS used:
使用的CSS:
.cpos {
position: relative;
top: -1.65em;
left: 1.8em;
}
The JQuery used:
使用的JQuery:
var p=null; /* Initialize variable p. */
p=$("b").detach(); /* Detach every possible <b>b</b>-tags. */
var p=$("<b>Console loaded!</b>").addClass("cpos"); /* Do anything, like adding class. */
p.appendTo("#container"); /* Append new data to the anchor container. */
Maybe you could use this for reference when animating. 也许您可以在动画时使用它作为参考。 ;)
;)
您可以解除处理程序末尾的单击处理程序,以便它永远不会再次触发:
$('.link1').off('click');
Use a flag 使用旗帜
var noRun = 0
$('.link1').click(function(){
if(noRun==1) {
return
}
noRun = 1
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
});
You can save a simple "token" to check if is the first time that click is fired in this way: 您可以保存一个简单的“令牌”来检查是否是第一次以这种方式触发点击:
$('.link1').click(function(){
if(!$(this).data('isFirstTime')) {
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
$(this).data('isFirstTime', true);
}
});
This should prevent further click 这可以防止进一步点击
This should do it 这应该做到这一点
(function(){
var first=true;
$('.link1').click(function(){
if (first){
first=false;
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
}
});
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.