0
点赞
收藏
分享

微信扫一扫

原生JS实现各种运动之重心运动


给大家分享一个用原生JS实现的重心运动,所谓重心运动即为一个元素在向下运动触底时呈一定角度的递减回弹,效果如下:

原生JS实现各种运动之重心运动_JavaScript

实现代码如下,欢迎大家复制粘贴及吐槽。  

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现各种运动之重心运动</title>
<style>
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>
</head>

<body>

<input type="button" value="开始运动" onclick="startMove()" />

<div id="box"></div>

<script>

var speedX = 10;
var speedY = 10;

function startMove() {

setInterval(function () {

var box = document.getElementById('box');

// 将Y轴增加速度,实现重力运动
speedY += 10;

var left = box.offsetLeft + speedX;
var top = box.offsetTop + speedY;

// 当元素碰到底边时
if (top >= document.documentElement.clientHeight - box.offsetHeight) {
// 速度递减
speedY *= -0.8;
speedX *= 0.8;
// 误差强行赋值
top = document.documentElement.clientHeight - box.offsetHeight;
// 当元素碰到上边时
} else if (top <= 0) {
// 速度递减
speedY *= -0.8;
speedX *= 0.8;
// 误差强行赋值
top = 0;
};

// 当元素碰到右边时
if (left >= document.documentElement.clientWidth - box.offsetWidth){
// 速度递减
speedX *= -0.8;
// 误差强行赋值
left = document.documentElement.clientWidth - box.offsetWidth;
// 当元素碰到左边时
} else if (left <= 0) {
// 速度递减
speedX *= -0.8;
// 误差强行赋值
left = 0;
};

// 当X轴的速度绝对值小于0时
if (Math.abs(speedX) < 1) {
// 强行终止
speedX = 0;
};

// 当Y轴的速度绝对值小于0时
if (Math.abs(speedY) < 1) {
// 强行终止
speedY = 0;
};

box.style.left = left + 'px';
box.style.top = top + 'px';

}, 30);
}
</script>
</body>

</html>

举报

相关推荐

0 条评论