getBoundingClientRect()来获取页面元素的位置”

2023-06-12,,

getBoundingClientRect()来获取页面元素位置

获取的是一个对象;

延伸阅读;

https://mp.weixin.qq.com/s?__biz=MzAxODE2MjM1MA==&mid=403029188&idx=2&sn=1088e273b855b75815edb2e7977a0513&scene=0&key=710a5d99946419d988a823a3f76c4dabc336d68c1e192697aba3d5cdba0fce0f3dcb6b78a1934ce2f133ceeaab13180f&ascene=0&uin=MjY5MTA1NTUyNg%3D%3D&devicetype=iMac+MacBookAir7%2C2+OSX+OSX+10.10.5+build(14F1509)&version=11020012&pass_ticket=0TjAxgbmAwJ36hKBl6%2FKYh6xGq2b%2F%2BtEvMKL4mdzjFQTBk5DbaxNFQJwTuWK9VBv

 <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#w3124{
width: 100px;
height:100px;
background:#f45;
position: absolute;
left:100px;
}
#w3124.totes-at-the-end{
top: 200px;
}
#w3124.animate-on-transforms{
transition: all 1s; }
</style>
</head>
<body>
<div id="w3124" class=""> </div>
<script>
console.log(document.getElementById("w3124").getBoundingClientRect());
var el = document.getElementById("w3124");
function tidyUpAnimations(){
console.log(222)
}
// 获取初始位置
var first = el.getBoundingClientRect(); // 为元素指定一个样式,让元素在最终位置上
el.classList.add('totes-at-the-end'); // 获取最终位置
var last = el.getBoundingClientRect(); // 如果有必要也可以对其他样式进行计算,但最好坚持只进行 transform 和 opacity 相关的计算
var invert = first.top - last.top;
console.log(invert); // 反转
el.style.transform = 'translateY(' + invert + 'px)'; // 等到下一帧,也就是其他所有的样式都已经被应用
requestAnimationFrame(function() { // 添加动画相关的设置
el.classList.add('animate-on-transforms'); // 开始动画
el.style.transform = '';
},5000); // 结束时清理
el.addEventListener('transitionend', tidyUpAnimations);
</script>
</body>
</html>

getBoundingClientRect()来获取页面元素的位置”的相关教程结束。

《getBoundingClientRect()来获取页面元素的位置”.doc》

下载本文的Word格式文档,以方便收藏与打印。