說明: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
}
複製代碼