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

clientWidth、clientHeight、offsetWidth、offsetHeight以及scrollWidth、scrollHeight是几个困惑了好久的元素属性,趁着有时间整理一下

1. clientWidth 和 clientHeight 

网页中的每个元素都具有 clientWidth 和 clientHeight 属性,表示可视区域的宽高,即元素内容加上padding以后的大小,而不包括border值和滚动条的大小,

如下图所示:

示例代码如下:

HTML代码:

<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;
}

如下图:

从上图得出:

clientWidth = 内容 + padding 即 83+30*2 = 143

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

 

posted @ 2017-02-10 18:11  桔子_Lynn  阅读(375)  评论(1编辑  收藏  举报