说明:javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style> body { margin: 0; } #box { position: relative; width: 300px; height: 300px; background-color: red; overflow: hidden; margin: 50px; } #child { width: 100px; height: 100px; background-color: blue; margin: 30px; border: 10px solid yellow; padding: 10px; } </style>
</head>
<body>
<div id="box">
<div id="child">
</div>
</div>
<script> var box = document.getElementById('box'); console.log(box.offsetTop);//50,父级没有定位,相对body console.log(box.offsetLeft);//50,父级没有定位,相对body var child = document.getElementById('child'); console.log(child.offsetTop);//30,父级有定位,相对box console.log(child.offsetLeft);//30,父级有定位,相对box </script>
</body>
</html>
复制代码
说明:css
content+padding*2+border*2
<script>
var box = document.getElementById('box');
console.log(box.offsetWidth);//300
console.log(box.offsetHeight);//300
var child = document.getElementById('child');
console.log(child.offsetTop);//140
console.log(child.offsetLeft);//140
</script>
复制代码
注意:html
说明:java
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style> body { margin: 0; } #box { width: 100px; height: 100px; margin: 50px; border: 45px solid red; padding: 10px; background-color: green; } </style>
</head>
<body>
<div id="box">
</div>
<script> var box = document.getElementById('box'); console.log(box.clientLeft);//45 console.log(box.clientTop);//45 </script>
</body>
</html>
复制代码
说明:ui
console.log(box.clientWidth);//120
console.log(box.clientHeight);//120
复制代码
说明:spa
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style> body { margin: 0; } #box { width: 100px; height: 100px; margin: 50px; border: 30px solid red; padding: 10px; background-color: green; overflow: auto; } </style>
</head>
<body>
<div id="box">
小明跟小华到动物园玩,进门时,小明指着小华对看门人说:“看清楚喔!等会儿出来,别说我偷了大家的猴子!”
</div>
<script> var box = document.getElementById('box'); // 当拖动box中的滚动条的时候触发 box.onscroll = function () { console.log(box.scrollLeft); console.log(box.scrollTop); } </script>
</body>
</html>
复制代码
说明:code
console.log(box.scrollWidth);//103
console.log(box.scrollHeight);//269,比较难测
复制代码
说明:htm
bar.onclick=function(e){//鼠标点击事件,其余事件也能够
e=e||window.event;
//获取鼠标
var x=e.pageX
var y=e.pageY
}
复制代码