Jquery 单击时将字体大小动画回原始大小

Jquery animate fontSize back to original size on click

JSFIDDLE

$("button").click(function(){
$("h1").animate({fontSize: "50px"});

如果再次单击,如何使字体大小 return 恢复到原来的大小。

您可以通过检查当前字体大小然后切换要设置的值来实现此目的,如下所示:

$("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>

也就是说,在 CSS 中进行过渡并在 JS 代码中切换元素上的 class 会更好(并产生更平滑的效果),就像这样:

$("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>

你可以使它基于 CSS,这样可以减少 JS 部分:

$("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>