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新手小白的记录

相关文章
相关标签/搜索