放大缩小字体示例

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="add">放大</button>  <button id="min">缩小</button>
    <div id="txt">陋室铭 斯是陋室惟吾德馨</div>

    <script>
        var add = document.getElementById('add');
        var min = document.getElementById('min');
        var txt = document.getElementById('txt');

        // 放大按钮
        var num = 16;
        add.onclick = function(){
            num +=2;  // 等同于num = num + 2
            console.log(num);
            
            if(num >= 40){
                num = 40;
            }
            txt.style.fontSize = num + 'px';
            
        }

        // 缩小按钮
        min.onclick = function(){
            num -= 2;
            if(num <= 12){
                num = 12;
            }
            txt.style.fontSize = num + 'px';
        }
    </script>
</body>
</html>

 

效果

posted @ 2020-07-03 12:42  石海莹  阅读(582)  评论(0编辑  收藏  举报