zoukankan      html  css  js  c++  java
  • JavaScript如何获取网页的宽高,以及如何兼容(各种坑详解)

    方式一:window.innerWidth / window.innerHeight

    这种方式只支持IE9以及以上版本的浏览器


    网页高度,打开F12控制台当然高度会不同

    方式二:document.documentElement.clientWidth

    console.log(document.documentElement);
    console.log(document.documentElement.clientWidth);
    console.log(document.documentElement.clientHeight);

    document.documentElement获取到的是html,从而获取到了整个网页

    可用于IE9以下,当然也支持IE9以及以上 可以用来兼容

    方式三:混杂模式/怪异模式 下的宽高的获取

    怪异模式:没有写文档声明(就是第一行的那个< !DOCTYPE html >)就是怪异模式,这种模式下会有一些不同的渲染方式,感兴趣的小伙伴可以去了解(这里讲解的获取宽高就是怪异模式特点之一)。

    http://www.bijianshuo.com 软文发稿平台

    console.log(document.compatMode);
    console.log(document.body.clientWidth);
    console.log(document.body.clientHeight);

    这样获取的方式只有在混杂模式下可以正确获取,在标准模式下不会报错,但是获取到的宽高不是正确的。
    document.compatMode可以知道当前文档是混杂还是标准(BackCompat混杂,css1Compat标准)


    你以为结束了?
    问题才出现!~
    所以,问题来了:怎么兼容?(别认为兼容不重要,不兼容就有很大的报错风险啊喂!毕竟你不知道用户会不会用IE6打开网页@_@)
    封装:兼容了高低版本浏览器,标准/混杂模式

    function getWid_Hei(){
    let width,height;
    if(window.innerWidth){
    width = window.innerWidth;
    height = window.innerHeight;
    }else if(document.compatMode === "BackCompat"){
    width = document.body.clientWidth;
    height = document.body.clientHeight;
    }else{
    width = document.documentElement.clientWidth;
    height = document.documentElement.clientHeight;
    }
    return {
    width,
    height:height
    }
    }
    let {width,height} = getWid_Hei();
    console.log(width,height);
  • 相关阅读:
    WebSocket来实现即时通讯
    微信小程序1
    使用phpqrcode来生成二维码/thinkphp
    PHP函数积累
    Docker 常用命令汇总(beta)
    Nginx+Keepalived高可用架构简述(beta)
    Docker镜像制作(以Nginx+Keepalived为例)(beta)
    开源协议浅谈(beta)
    【Elasticsearch系列】ES安装(mac)
    linux 下安装JDK
  • 原文地址:https://www.cnblogs.com/qianxiaox/p/14982591.html
Copyright © 2011-2022 走看看