html 縮放頁面樣式不亂(動態設置rem的跟字體大小rem布局實現)


主要核心代碼(通過動態獲取瀏覽器窗口寬度給html設置font-size,然后使用rem布局實現縮放頁面樣式不亂掉):

<script>
    ;(function(win) {
        var tid;
        function refreshRem() {
            let designSize = 1920; // 設計圖尺寸
            let html = document.documentElement;
            let wW = html.clientWidth;// 窗口寬度
            let rem = wW * 100 / designSize;
            document.documentElement.style.fontSize = rem + 'px';
        }

        win.addEventListener('resize', function() {
            clearTimeout(tid);
            tid = setTimeout(refreshRem, 300);
        }, false);
        win.addEventListener('pageshow', function(e) {
            if (e.persisted) {
                clearTimeout(tid);
                tid = setTimeout(refreshRem, 300);
            }
        }, false);

        refreshRem();

    })(window);
</script>

 

截不到瀏覽器的 縮放大小手動輸大小吧

放到最小25%:

 

 

 

 

 

 

放到最大500%:

 

 

 

先上列子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <title>Document</title>
    <style>
        body, html {
            margin: 0px;
        }
        .wenzi {
            margin: 0 auto;
            padding: 0.2rem;
            width: 3rem;
            font-size: 0.16rem;
            box-sizing: border-box;
            border: 0.03rem solid #61a4f1;
            text-align: center;
        }
        .wenzi img {
            width: 1rem;
            margin: 0 auto;
        }
    </style>
</head>
<body>
 <div class='wenzi'>
     <p>文字文字文字文字文字文字文字</p>
     <img src="./東方明珠.png" alt="">
     <img src="./東方明珠.png" alt="">
 </div>
    
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
    ;(function(win) {
        var tid;
        function refreshRem() {
            let designSize = 1920; // 設計圖尺寸
            let html = document.documentElement;
            let wW = html.clientWidth;// 窗口寬度
            let rem = wW * 100 / designSize;
            document.documentElement.style.fontSize = rem + 'px';
        }

        win.addEventListener('resize', function() {
            clearTimeout(tid);
            tid = setTimeout(refreshRem, 300);
        }, false);
        win.addEventListener('pageshow', function(e) {
            if (e.persisted) {
                clearTimeout(tid);
                tid = setTimeout(refreshRem, 300);
            }
        }, false);

        refreshRem();

    })(window);
</script>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM