问题
JSFIDDLE
$("button").click(function(){
$("h1").animate({fontSize: "50px"});
How to make the font size return to its original size if clicked again.
回答1:
You can achieve this by checking the current font size and then toggle the value to set, like this:
$("button").click(function() {
$("h1").animate({
fontSize: $('h1').css('font-size') == '32px' ? "50px" : '32px'
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>CLICK</button>
<h1>HELLO</h1>
That said, it would be better practice (and result in a smoother effect) to do the transition in CSS and just toggle the class on the element in your JS code, like this:
$("button").click(function() {
$("h1").toggleClass('large');
})
h1 { transition: all 0.5s; }
.large { font-size: 50px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>CLICK</button>
<h1>HELLO</h1>
回答2:
You can make it CSS based, which makes the JS part less:
$("button").click(function(){
$("h1").toggleClass('size-50');
})
.size-50{
font-size:50px;
}
h1{
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-o-transition: all 1s ease;
-ms-transition: all 1s ease;.toggle
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
CLICK
</button>
<h1>
HELLO
</h1>
来源:https://stackoverflow.com/questions/45078000/jquery-animate-fontsize-back-to-original-size-on-click