JavaScript-获取元素宽高

获取元素宽高

getComputedStyle

注意:

  • 读取的范围是 content 的值

  • 既能读取行内,也可以读取 css 设置的样式

  • 只可以读取,不可以设置

  • 只支持 IE9 及以上的高级浏览器

    geyComputedStyle(oDiv).width
    getComputedStyle(oDiv).height

currentStyle

  • 读取的范围是 content 的值

  • 既能读取行内,也可以读取 css 设置的样式

  • 只可以读取,不可以设置

  • 只支持 IE9 以下的低级浏览器

    oDiv.currentStyle.width
    oDiv.currentStyle.height

style

  • 读取的范围是 content 的值

  • 只能读取行内,不能读取 css 设置的样式

  • 即可以读取,也可以设置

  • 高级低级浏览器都支持

    oDiv.style.width
    oDiv.style.height

offsetWidth / offsetHeight

  • 读取的范围是 content + padding + border 的值

  • 既可以读取行内,也可以读取 css 设置的样式

  • 只可以读取,不可以设置

  • 高级低级浏览器都支持

    oDiv.offsetWidth
    oDiv.offsetHeight

client

  • clientWidth / clientHeight 获取到的宽高是 content + padding

  • clientTop / clientLeft 获取到的宽高是上边框和左边框

    oDiv.clientWidth / oDiv.clientHeight
    oDiv.clientTop / oDiv.clientLeft

获取网页可视区域宽高

  • 高级浏览器

    window.innerWidth
    window.innerHeight
  • 低级浏览器

    // 标准模式
    documnet.documentElement.clientWidth
    document.documentElement.clientHeight
    
    // 怪异模式 / 复杂模式
    document.body.clientWidth
    document.body.clientHeight
  • 兼容性写法

    function getScreen() {
        if (window.innerWidth){
            return {
                screenWidth: window.innerWidth,
                screenHeight: window.innerHeight
            }
        }else if (document.compatMode === "CSS1Compat"){ // 判断网页是否为怪异模式
            return {
                screenWidth: document.body.clientWidth,
                screenHeight: document.body.clientHeight
            }
        }else {
            return {
                screenWidth: document.documentElement.clientWidth,
                screenHeight: document.documentElement.clientHeight
            }
        }
    }

猜你喜欢

转载自www.cnblogs.com/luwenfeng/p/11693793.html
今日推荐