现象
getBoundingClientRect.gif
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=0.2, maximum-scale=3">
<title>Get Bounding Client Rect Test</title>
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#rect {
width: 50px;
height: 50px;
margin-top: 100px;
margin-left: 50px;
border: 2px solid red;
}
</style>
</head>
<body>
<div id="rect">
<div id="coordinate"></div>
</div>
</body>
<script>
var $el = document.getElementById('rect')
var $coordinate = document.getElementById('coordinate')
window.addEventListener('scroll', () => {
var rect = $el.getBoundingClientRect()
var xy = `x: ${rect.left}, y: ${rect.top}`
$coordinate.innerHTML = xy
console.log(xy)
})
</script>
</html>