clientWidth、clientHeight、offsetWidth、offsetHeight以及scrollWidth、scrollHeight

clientWidth、clientHeight、offsetWidth、offsetHeight以及scrollWidth、scrollHeight是幾個困惑了很久的元素屬性,趁着有時間整理一下javascript

1. clientWidth 和 clientHeight html

網頁中的每一個元素都具備 clientWidth 和 clientHeight 屬性,表示可視區域的寬高,即元素內容加上padding之後的大小,而不包括border值和滾動條的大小,java

以下圖所示:spa

示例代碼以下:code

HTML代碼:htm

<div id="demo">
    <p></p>
</div>

CSS代碼:對象

div{
    width: 100px;
    height: 100px;
    overflow: scroll;
    border:20px solid #7b7676;
    padding: 30px;
    margin: 60px;
}
p{
    width: 180px;
    height: 160px;
    background: #aac7aa;
}

以下圖:
blog

從上圖得出:ip

clientWidth = 內容 + padding 即 83+30*2 = 143element

clientHeight = 內容 + padding 即 83+30*2 = 143

2. scrollWidth 、scrollHeight 、scrollLeft、scrollTop

scrollWidth 和 scrollHeight 表示內容的完整寬高,包括padding以及沒有徹底顯示出來的部分,不包括滾動條

scrollWidth = padding+包含內容的徹底寬度

scrollHeight = padding+包含內容的徹底高度

scrollLeft和scrollTop都表示滾動條滾動的部分

以下圖:

依然利用上面的例子:

scrollWidth:160 + 30 = 190

scrollHeight:180 + 30 = 210

至於爲何padding只加30而不是30*2呢,如上圖所示,超出隱藏部分距離父元素邊框是沒有padding的,因此只加一個

3. offsetWidth  和 offsetHeight

   以下圖所示:

offsetWidth表示元素自己的寬度,包括滾動條和padding,border

offsetHeight表示元素自己的高度,包括滾動條和padding,border

因此例子中的offsetWidth = 100 + 20 * 2 + 30 * 2 = 200

                            offsetHeight = 100 + 20 * 2 + 30 *2 = 200

offsetTop 和 offsetLeft 表示該元素的左上角與父容器(offsetParent對象)左上角的距離

參考連接:http://www.ruanyifeng.com/blog/2009/09/find_element_s_position_using_javascript.html

by新手小白的記錄

相關文章
相關標籤/搜索