I have here a little script to change the height of my Div but actually it's only getting smaller. How can I toggle it to get it back higher again?
$( ".div1" ).click(function() {
$(".div2").animate({
height: ($(this).height() == 40) ? 10 : 40
}, 200);
});
Issue is that $(this)
refers to $( ".div1" )
not $( ".div2" )
$( ".div1" ).click(function() {
$(".div2").animate({
height: $(".div2").height() == 40 ? 10 : 40
}, 200);
});
Full Codepen: https://codepen.io/anon/pen/zrRboZ
You can use an if-then
statement:
$(document).ready(function() { var boolean = false; $(".div1").click(function() { boolean = !boolean; if (boolean) { $(".div2").animate({ height: "+=20px" }, 200); } else { $(".div2").animate({ height: "-=20px" }, 200); } }); });
.div1 { background-color: red; } .div2 { background-color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="div1">Foo</div> <div class="div2">Bar</div>
Also, I would use a relative height
so it changes back to the same value.
This may be a bit obscure, but you can use modular arithmetic.
Notice that:
(40 + 30) % 60 == 10
(10 + 30) % 60 == 40
(40 + 30) % 60 == 10
and so on
So, in other words, you can just do
$( ".div1" ).click(function() {
$(".div2").animate({
height: ($(".div2").height()+30)%60
}, 200);
});
PS: beware of the use of this, if you are not clear you may be referring to a different object, in this case, $(".div1")
you can use toggleClass:
.div2{height:40px;}
.div2.smaller{height:10px;}
$('.div1').click(function(){$('.div2').toggleClass('smaller');});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.