JS中标签的占位及定位 clientWidth、offsetWidth、scrollWidth等的区别

发布于 2020-04-09  632 次阅读


 一.client

所谓占位,就是标签所占的面积
一般是 宽,高,padding,margin,border
执行结果,都是数值,没有px单位,可以直接使用

1.clientWidth的实际宽度

       clientWidth = width+左右padding

2.clientHeigh的实际高度

       clientHeigh = height + 上下padding

3.clientTop的实际宽度

        clientTop = boder.top(上边框的宽度)

4.clientLeft的实际宽度

        clientLeft = boder.left(左边框的宽度)

如果需要 获取 右下 只能使用 css样式属性获取

        // 获取 右 / 下 边框线数据
        console.log( myGetStyle(oDiv , 'borderRightWidth') );
        console.log( myGetStyle(oDiv , 'borderBottomWidth') );
        // 获取标签css样式的兼容语法函数
        // 参数1: 需要获取样式的标签对象
        // 参数2: 需要获取样式的属性名称
        function myGetStyle(element, style) {
            // 如果 浏览器 支持 window.getComputedStyle    执行结果有内容,自动转化为 true
            // 如果 浏览器 不支持 window.getComputedStyle  执行结果,为undefined,自动转化为 false
            if (window.getComputedStyle) {
                // window.getComputedStyle 转化为 true 的情况
                // 也就是 浏览器 支持 window.getComputedStyle 可以使用
                return window.getComputedStyle(element)[style];
            } else {
                // window.getComputedStyle 转化为 false 的情况
                // 浏览器不支持 window.getComputedStyle 方法  不能使用
                return element.currentStyle[style];
            }
        }

二.offset

1.offsetWidth的实际宽度

       offsetWidth = width + 左右padding + 左右boder

2.offsetHeith的实际高度

       offsetHeith = height + 上下padding + 上下boder

3.offsetTop实际宽度

       offsetTop:当前元素上边框外边缘到最近的已定位父级(offsetParent)上边框内边缘的距离。

4.offsetLeft实际宽度

       offsetLeft:当前元素左边框外边缘到最近的已定位父级(offsetParent)左边框内边缘的距离。

找定位父级是谁

如果记不清楚 , console.dir(标签对象) 自己看看就行了

标签没有定位,父级没有定位, 定位父级是 body

标签有定位,父级没有定位

relative ---- body
absolute ---- body
fixed ---- null 视窗窗口

标签有定位,父级也有定位

父级有定位,当前标签是 relative  absolute
定位父级是 父级标签

父级有定位,当前标签是 fixed

定位父级是 null 视窗窗口

三.scroll

1.scrollWidth实际宽度

       scrollWidth:获取指定标签内容层的真实宽度(可视区域宽度+被隐藏区域宽度)。

2.scrollHeight的实际高度

       scrollHeight:获取指定标签内容层的真实高度(可视区域高度+被隐藏区域高度)

3.scrollTop

       scrollTop :内容层顶部到可视区域顶部的距离。

实例:

        // 兼容获取高度的方式:
        var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        // 持续获取高度的方式:
        window.addEventListener('scroll', ()=>{
            var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        });

4.scrollLeft

        scrollLeft:内容层左端 到 可视区域左端的距离.

四.inner

包括滚动条宽度高度

        window.innerWidth
        window.innerHeight

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。