JavaScript-offsetWidth,clientWidth,scrollWidth,及对应top、left区别及实测结果

1.div里面包裹text

HTML:

<div class="outerdiv">
BEIJING - A new round of smog is likely to hit Beijing and neighboring regions Saturday night and will stay for at least four days, the local weather bureau said Saturday.......
</div>

CSS:

             *{
			margin:0;
			padding:0;
		}
		.outerdiv{
			overflow: scroll;
			border:1px solid #DDD;
			width:300px;
			height:300px;
			margin:100px 50px;
			font-size: 10pt;
		}

JS:

                var eldiv=document.getElementsByClassName("outerdiv")[0];
		console.log('clientWidth: '+eldiv.clientWidth);
		console.log('offsetWidth: '+eldiv.offsetWidth);
		console.log('scrollWidth: '+eldiv.scrollWidth);
		console.log('clientTop: '+eldiv.clientTop);
		console.log('offsetTop: '+eldiv.offsetTop);
		console.log('scrollTop: '+eldiv.scrollTop);
		console.log('clientLeft: '+eldiv.clientLeft);
		console.log('offsetLeft: '+eldiv.offsetLeft);
		console.log('scrollLeft: '+eldiv.scrollLeft);
结果:

      FireFox & Chrome & IE

             

 

结论: clientWidth与scrollWidth 仅仅指内容宽度,不包括滚动条和边框。 offsetWidth指内容+滚动条+边框 宽度。offsetTop与offsetLeft指边框到父元素的距离,本例子中与     margin值相同。clientTop与clientLeft与border宽度相同。scrollTop与scrollLeft与滚动条上下或左右滚动的宽度大小相同。

2. outerdiv包裹innerdiv,innerdiv包裹text

HTML:

<div class="outerdiv">
	<div class="innerdiv">
		BEIJING - A new round of smog is likely to hit Beijing and neighboring regions Saturday night and will stay for at least four days, the local weather bureau said Saturday.......
	</div>
</div>

CSS:

              *{
			margin:0;
			padding:0;
		}
		.outerdiv{
			overflow: scroll;
			border:1px solid #DDD;
			width:300px;
			height:300px;
			margin:100px 50px;
			font-size: 10pt;
		}
		.innerdiv{
			width:500px;
			height:500px;
		}

JS:

<script>
		var eldiv=document.getElementsByClassName("outerdiv")[0];
		var txdiv=document.getElementsByClassName("innerdiv")[0];
		console.log('outer div');
		console.log('clientWidth: '+eldiv.clientWidth);
		console.log('offsetWidth: '+eldiv.offsetWidth);
		console.log('scrollWidth: '+eldiv.scrollWidth);
		console.log('clientTop: '+eldiv.clientTop);
		console.log('offsetTop: '+eldiv.offsetTop);
		console.log('scrollTop: '+eldiv.scrollTop);
		console.log('clientLeft: '+eldiv.clientLeft);
		console.log('offsetLeft: '+eldiv.offsetLeft);
		console.log('scrollLeft: '+eldiv.scrollLeft);
		console.log('inner div');
		console.log('clientWidth: '+txdiv.clientWidth);
		console.log('offsetWidth: '+txdiv.offsetWidth);
		console.log('scrollWidth: '+txdiv.scrollWidth);
		console.log('clientTop: '+txdiv.clientTop);
		console.log('offsetTop: '+txdiv.offsetTop);
		console.log('scrollTop: '+txdiv.scrollTop);
		console.log('clientLeft: '+txdiv.clientLeft);
		console.log('offsetLeft: '+txdiv.offsetLeft);
		console.log('scrollLeft: '+txdiv.scrollLeft);
	</script>

结果:

                       

outer div各项值与1中结果相同





你可能感兴趣的:(JavaScript,top,left,scrollwidth,clientwidth,offeetwidth)