Jquery animate fontSize back to original size on click

荒凉一梦 提交于 2019-12-24 06:52:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!