rem的正确使用姿势 -- 完美解决H5页面不同尺寸屏幕的适配问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fifteen718/article/details/83039121

实例代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>废土坱行</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style type="text/css">
    * {
        margin: 0;
        padding: 0;
    }
    .downloadBtn {
        width: 12rem;
        height: 3.6rem;
        background: red;
        position: absolute;
        left: 50%;
        top: 29.6rem;
        margin-left: -6rem;
        font-size: 1rem;
    }
    </style>
</head>
<body>
    <div class="content">
        <img class="contentImg" id="contentImg" src="./images/content.png"/>
        <button class="downloadBtn">立即下载</button>
    </div>
    <script>
        function initWidth() {
            document.getElementById("contentImg").style.width = document.documentElement.clientWidth + 'px'
        }
        function initFontSize() {
            const cw = document.documentElement.clientWidth
            // width: 375px -> fontSize:16px
            if (cw == 375) {
                document.documentElement.style.fontSize = '16px'
            } else {
                document.documentElement.style.fontSize = cw / 375 * 16 + 'px'
            }
        }
        initWidth()
        initFontSize()
        window.onresize = () => {
            initWidth()
            initFontSize()
        }
    </script>
</body>
</html>

 

思路简介:

1、首先,界面布局的尺寸采用rem单位。

2、然后,通过设置根节点(html)的 font-size 的 px 值 来影响 rem 的实际大小。

3、最后,通过 js 来实时控制font-size 的大小,等比例变换即可。

 

效果演示:

标准尺寸下(iphone6):

其它设备上(比如iphone5):

注:可以看到我这个“立即下载”的按钮位置基本上是可以和img对上的。

猜你喜欢

转载自blog.csdn.net/fifteen718/article/details/83039121
今日推荐