DOM中的scrollWidth(Height/Left/Top),offsetWidth(Height/Left/Top)以及clientWidth(Height/Left/Top)
(1)测试代码如下:
<style type="text/css"> *{ margin: 0; padding: 0; } #myDiv{ width: 100px; padding: 5px; height: 100px; border: #000 5px solid; margin: 100px; overflow:scroll; } </style> </head> <body> <div id="myDiv"> <p>content content content content content content content content </p> </div> <script type="text/javascript"> var sl=myDiv.scrollLeft, st=myDiv.scrollTop, sw=myDiv.scrollWidth, sh=myDiv.scrollHeight, ow=myDiv.offsetWidth, oh=myDiv.offsetHeight, ol=myDiv.offsetLeft, ot=myDiv.offsetTop, cw=myDiv.clientWidth, ch=myDiv.clientHeight, cl=myDiv.clientLeft, ct=myDiv.clientTop; alert( 'sl:'+sl+'\n'+ 'st:'+st+'\n'+ 'sw:'+sw+'\n'+ 'sh:'+sh+'\n'+ 'ow:'+ow+'\n'+ 'oh:'+oh+'\n'+ 'ol:'+ol+'\n'+ 'ot:'+ot+'\n'+ 'cw:'+cw+'\n'+ 'ch:'+ch+'\n'+ 'cl:'+cl+'\n'+ 'ct:'+ct); </script>
如图:
浏览器:chrome22 firefox12.0 IE9&IE6
弹出结果显示除scrollHeight外,其他值均相同(注意:测试前要保证html文档结构完整,注明文档声明。如果漏掉文档声明,会造成ie中盒子模型出现问题从而导致弹出结果发生变化。)
弹出值如下:
(2)根据以上css值来解释一下scroll--offset--client
scrollWidth(元素内内容的宽度不包含边性质的border、scrollbar等)=width+padding-scrollbarWidth;
scrollHeight(和scrollWidth原理相同)=Height+padding-scrollbarHeight;
针对scrollWidth和scrollHeight,需要注意的是:当内容的宽度或高度超出实际宽/高度(如css定义的宽高)的时候,scrollWidth/Height才会显示出其特性,其值将会是实际内容的宽高度(大于容器的实际宽/高度)。
关于scrollLeft和scrollTop,该测试没有体现出来。其实,这两个值也是在内容超出元素的时候才会体现出来。比如宽为100px,但实际内容其实为150px,当拖动scrollbar到中间位置的时候,那么内容超出元素左右各25px,此时的scrollLeft即为25。因此,scrollLeft指的就是内容当前左边界距内容实际左边界的距离。scrollHeight与其原理相同。
offsetWidth(元素的可见宽度)=width+padding+border
offsetHeight(元素的可见高度)=height+padding+border
offsetLeft(元素可见左边界与离元素本身最近的左元素的边界间的距离)=margin-left
offsetTop(元素可见上边界与离元素本身最近的上元素的边界间的距离)=margin-top
clientWidth(元素内容的可见宽度,等同于元素内容不超出实际宽时的scrollWidth)=width+padding-scrollbarWidth;
clientWidth(元素内容的可见高度,等同于元素内容不超出实际高时的scrollHeight)=Height+padding-scrollbarHeight;