<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js中的元素运动原理</title>
<style>
div {
width: 50px;
height: 50px;
background: lightblue;
padding: 10px;
border: 2px solid red;
margin: 20px;
border-radius: 50%;
position: absolute;
top: 50px;
left:10px;
}
</style>
</head>
<body>
<button>动起来</button>
<div></div>
<script>
var btn = document.querySelector('button');
var ball = document.querySelector('div');
//offsetWidth(盒子的可视宽度): offsetWidth = width + padding + border
// 当前盒子可视宽度: 50 + 10*2 + 2*2 = 74 (数值不是字符串)
// offsetHeight(盒子的可视高度) 计算方式是一样的
console.log(ball.offsetWidth);
console.log(ball.offsetHeight);
// offsetLeft(盒子相对定位父级的左边相对位置): left + margin-left
console.log(ball.offsetLeft); // left + margin-left = 10 + 20 = 30
console.log(ball.offsetTop); // top + margin-top
console.log(ball.offsetParent); // <body>
console.log(ball.offsetParent.offsetWidth); // <body>
// 经过分析,只需要改变offsetLeft就可以使这个小球向右动起来
// 小球的margin-left不会改变,只要不断的改变left就可以
// 需要使用到定时器函数 setInterval()用于间歇执行某一函数
btn.onclick = function () {
var timer = null;
timer = setInterval(function () {
// 多次点击会创建多个定时器导致加速运动,所以在创建一个新定时器之前,先清除之前的定时器
clearInterval(timer);
// 如果让小球停下来?
if (ball.offsetLeft < 500) {
ball.style.left = ball.offsetLeft + 5+ 'px';
} else {
clearInterval(timer);
}
}, 200);
}
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
总结:
元素运动的原理是通过修改元素的offsetLeft和offsetTop实现的
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号