您的方法会导致大量代码重复。更好的选择是将字体差异存储在data-*属性中,并绑定一次hanlder。然后只需检查处理程序设置的上一个diff。
这将允许您在将来添加更多的链接(比如说非常小或非常大),而不需要触摸您的代码。
$('[data-font]').click((function(current){
return function(e) {
var $this = $(this),
font = parseInt($this.data('font')),
// remove previous diff and add new
diff = -current + font;
e.preventDefault();
// same button click
if(current === font) return
// save for the next call
current = font;
$('div').children().css('font-size', function() {
return parseFloat($(this).css('font-size')) + diff + 'px';
})
}
}(0)))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="" data-font="+3">Large</a>
<a href="" data-font="0">Medium</a>
<a href="" data-font="-3">Small</a>
<div>
<p>Lorem ispsum dolor</p>
<h1>Lorem ispsum dolor Lorem ispsum dolor Lorem ispsum dolor</h1>
<h3>Lorem Ipsum</h3>
</div>