js实现PC端与客户端自适应

我们可以通过js来判断页面对象进行显示,

在外部引入css设定ID

1 <link rel="stylesheet" id="css" type="text/css" href="css/pc.css"/>

js代码如下

var newDoc=document.open("text/html","replace"); //重新加载引入
        window.onload=function(){
            //进入判断页面
             changeDivHeight();
        }
        window.onresize=function(){
            //监听页面宽度值
             changeDivHeight();
        }
             //执行判断命令
             function changeDivHeight(){    
                   //获取body的宽度            
                    var h = document.body.clientWidth 
                    if(h < 800)
                    {
                    //移动端    
                    document.getElementById('css').href='css/web.css'  //客户端
                    
                    newDoc.close();
                    }
                    else
                    {
                    //PC端
                    document.getElementById('css').href='css/pc.css'  //PC端
                    newDoc.close();
                    }
        }

我用的方法是通过js来判断页面的高度来定义大小,我这边设定是宽度800px,超过800我这边设定为PC端页面,引入pc.css,宽度小于800px,我这边设定为web端也就是手机进行显示引入web.css。

posted @ 2019-09-11 08:38  这个靓仔有点儿彪  阅读(1224)  评论(0编辑  收藏  举报