在 JavaScript 中更改字体大小的函数。如何添加缩放限制?

5

我有一个函数:

    function changeFontSize(points) {
        var e = document.getElementsByTagName("BODY")[0];
        var style = window.getComputedStyle(e);
        var size = style.getPropertyValue('font-size');
        size = size.replace("px", "");
        size = size * 1;
        size = size + points;
        //if(size <= 0 && size  <= 3){
            e.style.fontSize = size + "px";
            localStorage.setItem("size", size);
        //}
    }

    function saveFontSize() {
        var size = localStorage.getItem("size");
        if (size !== null) {
            var e = document.getElementsByTagName("BODY")[0];
            e.style.fontSize = size + "px", '!important';
        }
    }

    document.addEventListener("DOMContentLoaded", saveFontSize);



<a href="#" onclick="changeFontSize(1);">plus</a>
<a href="#" onclick="changeFontSize(-1);">minus</a>

上述代码功能正常。

上述函数可以在我的网站上放大和缩小字体大小。

我需要限制此函数的作用范围,使其仅能将字体大小最多增加三倍。字体大小减小(较小字体)不能小于原始大小。

应该如何做? 请帮忙。

1个回答

3
您可以存储初始字体大小,然后利用 Math.minMath.max
body.style.fontSize = Math.max(
  initialBodyFontSize, 
  Math.min(
    initialBodyFontSize * 3, 
    getBodyFontSize() + points
  )
) + 'px';

演示(因为这里不可能进行通过 localStorage 加载/保存的部分,所以省去):

{
  var body = document.querySelector('body');
  var initialBodyFontSize;
  
  // Note: this supposes the body's font size is expressed in px
  function getBodyFontSize() { 
    return parseFloat(window.getComputedStyle(body).getPropertyValue('font-size'));
  }

  function changeBodyFontSize(points) {
    body.style.fontSize = Math.max(
      initialBodyFontSize, 
      Math.min(
        initialBodyFontSize * 3, 
        getBodyFontSize() + points
      )
    ) + 'px';
    console.log(body.style.fontSize);
  }

  document.addEventListener('DOMContentLoaded', function () {
    initialBodyFontSize = getBodyFontSize();
  });
}
<a href="#" onclick="changeBodyFontSize(1);">plus</a>
<a href="#" onclick="changeBodyFontSize(-1);">minus</a>

另外,请注意通常应避免使用onclick和类似的属性,而应优先使用关联DOM元素上的addEventListener JS调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接