-

动态设置html的font-size值 (适配文字大小)

通过JS动态判断网页宽度来设置html标签的font-size字体大小

JS动态设置html的font-size值

用JS来实现动态设置html的font-size值 (适配文字大小)。
查看演示: https://www.xiyueta.com/article/html-font-size/demo.html
查看演示>>


  • HTML页面

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态设置html的font-size值 (适配文字大小)</title>
</head>

<body>
    <h4>动态设置html的font-size值 (适配文字大小)</h4>
    <p>通过JS动态判断网页宽度来设置html标签的font-size字体大小</p>
    
    <script>
    (function() {
        var html = document.documentElement;

        function onWindowResize() {
            html.style.fontSize = html.getBoundingClientRect().width / 23.4375 + 'px';
        }
        window.addEventListener('resize', onWindowResize);
        onWindowResize();
    })();
    </script>
</body>

</html>