1.获取滚动条距离顶部的高度:
js:
document.body.scrollTop
jq:
$(document).scrollTop()
2.获取某元素的宽高:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{margin:0;padding:0;}
.block{margin:50px;padding:40px;border:30px solid #bbb;width: 100px;height:100px;}
</style>
</head>
<body>
<div class="block" id="block">block</div>
</body>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// js:
var oBlock = document.getElementById('block');
console.log(oBlock.clientWidth);//180 content+padding
console.log(oBlock.scrollWidth);//180 content+padding
console.log(oBlock.offsetWidth);//240 content+padding+border
/*clientWidth和scrollWidth 区别:
当网页的宽度大于浏览器的宽度时候,
document.body.clientWidth获取的是整网页的可视区域即浏览器的宽度,不算border,body盒模型的宽度content
document.body.scrollWidth获取的是整个网页的实际宽度*/
// jq:
console.log($('#block').width());//100 content
console.log($('#block').innerWidth());//180 content+padding
console.log($('#block').outerWidth());//240 content+padding+border
console.log($('#block').outerWidth(true));//340 content+padding+border+margin
</script>
</html>
3.获取某元素的left和top:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{margin:0;padding:0;}
html,body{width: 100%;height: 200%;}
div{padding:40px;border:30px solid #bbb;width: 100px;height:100px;}
.position{position: absolute;left:88px;top:66px;}
.block{margin-top: 1000px;}
</style>
</head>
<body>
<div class="position" id="position">position</div>
<div class="block" id="block">block</div>
</body>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// js:
var oPosition = document.getElementById('position'),
oBlock = document.getElementById('block');
// 获取距离页面顶部的top
console.log(oPosition.offsetTop);//66
console.log(oBlock.offsetTop);//1000
// 获取距离窗口顶部的top(当滚动条向下拉动700px之后)
console.log(oPosition.offsetTop-document.body.scrollTop);//-634
console.log(oBlock.offsetTop-document.body.scrollTop);//300
// jq:
console.log($('#position').offset().top);
console.log($('#block').offset().top);
console.log($('#position').offset().top-$(document).scrollTop());
console.log($('#block').offset().top-$(document).scrollTop());
</script>
</html>
js的offsetLeft是相对于父元素的left值。
offsetParent.offsetLeft是相对于上一个有定位的元素的left值(若没有找到定位元素,就是body)
若定位层数较多的时候,想得到相对于body的left:
function getPoint(obj){
var l = obj.offsetLeft,
t = obj.offsetTop;
if(obj.offsetParent != null){
l += getPoint(obj.offsetParent).l;
t += getPoint(obj.offsetParent).t;
}
return {l:l,t:t};
}