我尝试了很多不同的选项,并且我确信如果我知道自己在做什么,大多数选项都会起作用。
我想单击图像并将其放大并位于屏幕中央,然后我想单击同一张图像并将其恢复正常。
在下面的两个单独的脚本中,我删除了相反的效果,但我基本上使用了将 css 设置更改回 width:250、height:250 和 marginLeft:9% 的函数。
可以让它成功地放大图像,但一旦完全放大,它就会自动缩小。 我需要使功能放大,然后等到我再次单击图像才能缩小。
<script>
$('document').ready(function(){
$('.hello_mom').on('click', function(){
$('.lbs_lease').animate({
width:"350px",
height:"350px",
zIndex:"10",
marginLeft:"28.4%"
}, 500 );
});
});
</script>
<!--<script>//My idea with this second script was to set an initial variable that I would use to make the enlargement animation run (with an if statement) and the shrinking animation stop until the variable was changed at the end of the function. Once the variable changes the else statement would become true and run my reverse animation. However, it seems redundant when the animation still doesn't wait for another click to occur before it runs.
$a = 5;
$c = 10;
var b = $a;
if(b < $c) {
$('.lbs_lease').animate({
width:"350px",
height:"350px",
zIndex:"10",
marginLeft:"28.4%"
}, 500 )};
</script>-->
最佳答案
你有两种方法可以做到这一点..
1- 通过使用带有过渡的 addClass 和 removeClass
在 CSS 中
.imageClicked{
width:350px;
height:350px;
zIndex:10;
marginLeft:28.4%;
transition : 0.5;
}
js
$('document').ready(function(){
$('.hello_mom').on('click', function(){
if($('.lbs_lease').hasClass('imageClicked')){
$('.lbs_lease').removeClass('imageClicked');
}else{
$('.lbs_lease').addClass('imageClicked');
}
});
});
2-通过使用默认样式制作另一个动画并使用 bool 值 true 或 false
$('document').ready(function(){
var imgClicked = true;
$('.hello_mom').on('click', function(){
if(imgClicked == true){
$('.lbs_lease').animate({
width:"350px",
height:"350px",
zIndex:"10",
marginLeft:"28.4%"
}, 500 );
imgClicked = false;
}else{
$('.lbs_lease').animate({
//type your default style here
}, 500 );
imgClicked = true;
}
});
});
关于javascript - Jquery - 单击时反转动画(切换或 if/else),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33779785/