根据屏幕宽度设定文字大小

根据屏幕宽度设定文字大小的方法:

1.css3媒体查询:

    <style>
        @media screen and (max-width: 320px) {
            body {
                font-size: 14px;
            }
        }
        @media screen and (max-width: 480px) and (min-width: 321px) {
            body {
                font-size: 18px;
            }
        }
        @media screen and (max-width: 720px) and (min-width: 481px ){
            body {
                font-size: 22px;
            }
        }
        @media screen and (max-width: 800px) and (min-width: 721px ){
            body {
                font-size: 26px;
            }
        }
    </style>

  2.使用JS方法:

  a.根据屏幕宽度设定字体

    <script>
        function textSetting(){                  //根据屏幕宽度设定字体大小
            var root = document.documentElement; //获取属性根节点
            var w = root.clientWidth;            //获取屏幕宽度
            var fs = w <= 320 ? 14 : w >320 && w <= 480 ? 18 : 22;   //判断文字大小
            root.style.fontSize = fs + "px";
        }
        textSetting(); 
    </script>

  b.根据屏幕宽度计算文字大小

  <script>
        function textSetting(minWidth,maxWidth){   //根据屏幕宽度计算字体大(14~35px)
            let maxfs = 35;                        //最大字体
            var root = document.documentElement;
            var w = root.clientWidth;
            w = w > maxWidth ? maxWidth : w <minWidth ? minWidth : w;
            var fs = w / maxWidth * maxfs;
            root.style.fontSize = fs + "px";
        }
        textSetting(400,800);
  </script>

猜你喜欢

转载自www.cnblogs.com/syh119/p/9109572.html