天天看點

scrollWidth、clientWidth、offsetWidth的差別;

偏移量

  1. offsetWidth:元素在水準方向上占用的空間大小;包括元素的寬度、垂直滾動條寬度、邊框、padding;
  2. offsetHeight:元素的垂直方向上占用的空間大小;包括元素的高度、水準滾動條高度、邊框、padding;
  3. offsetLeft:元素的左外邊框與父級元素的左内邊框的距離;
  4. offsetTop:元素的上外邊框與父級元素的上内邊框的距離;
  5. offsetParent:傳回一個對象的引用, 這個對象是距離調用offsetParent的元素最近的(在包含層次中最靠近的),并且是已進行過CSS定位的容器元素。

要獲得某個元素在頁面上的左偏移量、上偏移量一樣: var oBox = document.getElementById("box");     function getElementLeft(obj){         var current = obj.offsetParent;         var thisLeft = obj.offsetLeft;         if(current != null){             thisLeft += current.offsetLeft;             current = current.offsetParent;         }         return thisLeft;     } console.log(getElementLeft(oBox));

客戶區:

  1. clientWidth:元素内容及其内邊距所占空間大小 ;padding、width;不包括:border和margin
  2. clientHeight:元素内容及其内邊距所占空間大小 ;padding、width;不包括:border和margin
  3. 不包括滾動條的占據的空間;一般用在确定浏覽器視口的時候;

    function getViewport(){         if(document.compatMode == "CSS1Compat"){             return {                 width : document.documentElement.clientWidth,                 height : document.documentElement.clientHeight             }         }else{             return {                 width : document.body.clientWidth,                 height : document.body.clientHeight             }         }     } 滾動大小:

  1. scrollWidth:在沒有内容的情況下,元素内容的總寬度;
  2. scrollHeight:在沒有内容的情況下,元素内容的總高度;
  3. scrollLeft:被隐藏在内容區域左側的像素數;
  4. scrollTop:被隐藏在内容區域右側的像素數;

scrollWidth,clientWidth,offsetWidth的差別 情況1: 元素内無内容或者元素内容不超過可視區域,滾動條不出現的情況下。

scrollWidth=clientWidth,兩者皆為内容可視區的寬度。

offsetWidth為元素的實際寬度。

scrollWidth、clientWidth、offsetWidth的差別;

情況2: 元素的内容超過可視區域,滾動條出現和可用的情況下;

scrollWidth>clientWidth。

scrollWidth為實際内容的寬度。

clientWidth是内容可視區的寬度。

offsetWidth是元素的實際寬度。

scrollWidth、clientWidth、offsetWidth的差別;

繼續閱讀