[英]On first click animate, on second reverse animation: how to?
I have read couple of others questions like this, but they are basically using deprecated .toggle()
function. 我已经阅读了其他几个类似的问题,但是它们基本上使用了不赞成使用的.toggle()
函数。 I'm struggling to achieve that div#p
on first click goes right and on second click goes back to starting position. 我正在努力实现div#p
的第一次单击正确,然后再次单击回到起始位置。
I wrote this code: 我写了这段代码:
$(function(){
$("#p").on("click", function(){
if ($("#p").data("right") == 'n') {
$("#p").animate({marginLeft:"50"}, 500);
$("#p").data("right", 'y');
} else {
$("#p").animate({marginLeft:"0"}, 500);
$("#p").data("right", 'n');
}
})
})
which is working with one big error : after page is loaded, first click fires nothing .(second and other clicks are switching animation action correctly). 这有一个大错误 : 在加载页面后,第一次单击不会触发任何动作 。(第二次单击和其他单击会正确切换动画动作)。
What's the catch here, how to correct this? 这里有什么收获,如何纠正?
$(function(){
$("#p").on("click", function(){
var state = parseInt( $(this).css('margin-left'), 10 ) > 0;
$(this).animate({marginLeft : state ? 0 : 50}, 500);
});
});
or with data, and accounting for undefined data values : 或包含数据,并考虑未定义的数据值:
$(function(){
$("#p").on("click", function(){
var state = $(this).data("right");
$(this).animate({marginLeft: (state ? 50 : 0)}, 500);
$(this).data("right", !state);
});
});
You're trying to fetch data-right
but I don't think you have set that already. 您正在尝试data-right
地获取data-right
但我认为您尚未设置该数据。 You should set it upon loading of your page so you can actually retrieve it. 您应该在加载页面时进行设置,以便可以实际检索它。 Either use .ready()
or just add data-right
to your <p>
使用.ready()
或仅向<p>
添加data-right
I wrote similar code with ideas from this thread. 我用这个线程的想法编写了类似的代码。 This is for 1 div but it can be rewrite to tag "p" as you used in this thread. 这是1 div,但可以像在此线程中使用的那样重写为标签“ p”。
$( ".content" ).click(function() {
if( $( this ).hasClass( "vysun" ) ){
var status = true;
$( this ).removeClass( "vysun" );
}
else{
var status = false;
$( this ).addClass( "vysun" );
}
$( this ).animate({width : status ? "33%" : "100px"}, 1500, "linear");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.