JavaScript元素位置与距离:client&scroll&offset&MouseEvent&滚动条宽度计算

client:

clientWidth/clientHeight:

  • 元素内部的宽度/高度,仅包含包含content和padding,不包含滚动条
  • clientWidth = content width + padding - scrollbar Width 
  • clientHeight = content Height + padding - scrollbar Height

clientLeft/clientTop:

元素的左border宽度,当文字方向为右至左且出现滚动条时(direction: rtl),需要加上滚动条宽度

clientLeft = border Width + scrollbar Width(对于行内元素这个值为0)

clientTop = borderTop

计算浏览器或元素滚动条宽度:

elem.offsetWidth - elem.borderLeftWidth - elem.borderRightWidth - elem.clientWidth

export default class myUtils {
     // 计算元素滚动条宽度
     static getScrollWidth(elemOrSelect) {
        if (!elemOrSelect) return;
        if (elemOrSelect.constructor === String) elemOrSelect = document.querySelector(elemOrSelect);
        //参数为html或body时获取浏览器默认滚动条宽度
        if (/BODY|HTML/.test(elemOrSelect.nodeName)) {
            elemOrSelect.style.padding = 0; 
            elemOrSelect.style.margin = 0;
            return window.innerWidth - elemOrSelect.clientWidth;
        }
        //兼容
        var style = elemOrSelect.currentStyle ? elemOrSelect.currentStyle : getComputedStyle(elemOrSelect).style;
        //获取某个元素滚动条宽度
        var width =
            elemOrSelect.offsetWidth
            - Math.ceil(parseFloat(style.borderLeftWidth))
            - Math.ceil(parseFloat(style.borderRightWidth))
            - elemOrSelect.clientWidth;
        return width;
    }
}

offsetWidth/offsetHeight/offsetLeft/offsetTop:

offsetWidth/offsetHeight: content + padding + border(包含滚动条)

offsetLeft:

offsetTop:

一张经典的图片:

猜你喜欢

转载自www.cnblogs.com/ltfxy/p/12275352.html
今日推荐