增加/减少页面上所有元素字体大小的有效方法

Effective Way of Increasing/Decreasing Font Size of All Elements on Page

本文关键字:字体 元素 方法 有效 增加      更新时间:2023-09-26

为了提高用户体验,我计划在我的网站(a-、a、a+)的所有页面上安装一个字体大小增加/减少/重置工具

我面临的问题是页面上不同元素使用的字体大小是不一致的。有些是14像素,有些是18像素,有些12像素,有些15像素。

因此,使用body标记来操纵字体大小将不会得到所需的结果。

是否有一种解决方案可以遍历每个元素(获得其当前大小),如果单击A+,则将其字体大小增加1,如果单击了A-,则将字体大小减少1,如果点击了A,则将重置回原始大小?

附言:我也对jQuery的解决方案持开放态度。

这就是为什么发明了emrem单元而不是pxrem是指根字体大小,这使得使用body{ font-size : 120% }; 可以非常容易地增加和减少整个文档的字体大小

但是,由于您不能使用rem,这里有一个使用jQuery的肮脏解决方案:

var $affectedElements = $("p"); // Can be extended, ex. $("div, p, span.someClass")
// Storing the original size in a data attribute so size can be reset
$affectedElements.each( function(){
  var $this = $(this);
  $this.data("orig-size", $this.css("font-size") );
});
$("#btn-increase").click(function(){
  changeFontSize(1);
})
$("#btn-decrease").click(function(){
  changeFontSize(-1);
})
$("#btn-orig").click(function(){
  $affectedElements.each( function(){
        var $this = $(this);
        $this.css( "font-size" , $this.data("orig-size") );
   });
})
function changeFontSize(direction){
    $affectedElements.each( function(){
        var $this = $(this);
        $this.css( "font-size" , parseInt($this.css("font-size"))+direction );
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p style="font-size : 30px">This text is initially 30px</p>
  <div>
    <p style="font-size : 20px">This text is initially 20px</p>
    <p style="font-size : 10px">This text is initially 10px</p>
    
  </div>  
</div>
<button id="btn-decrease">A-</button>
<button id="btn-orig">A</button>
<button id="btn-increase">A+</button>

您最好、最干净的选择是将rem与jQuery混合使用。

我的答案与上面的答案/你所要求的不同之处在于,这只会改变根字体的大小,而不是将所有的字体大小增加/减少1,它会向下级联,并使所有其他字体相应地缩放

$('#_biggify').on('click', function() {
  var fontSize = $('html').css('font-size');
  var newFontSize = parseInt(fontSize)+1;
  
  $('html').css('font-size', newFontSize+'px')
})
$('#_smallify').on('click', function() {
  var fontSize = $('html').css('font-size');
  var newFontSize = parseInt(fontSize)-1;
  
  $('html').css('font-size', newFontSize+'px')
})
$('#_reset').on('click', function() {
  $('html').css('font-size', '32px')
})
html {
  font-size: 32px;
}
.smaller {
  font-size: 0.5rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Here is a regular piece of text in your document
</div>
<div class="smaller">
Here is text that should be smaller than the rest
</div>
<button id="_biggify">
Make Bigger
</button>
<button id="_smallify">
Make Smaller
</button>
<button id="_reset">
Make Default
</button>

以下是一个JSFiddle:https://jsfiddle.net/Hybridx24/L3yzuvjr/