Js模拟重力场【Js动效】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模拟重力场</title>
<style>
.swapper{
width: 100px;
height: 100px;
position: absolute;
background: #008c8c;
border-radius: 50%;
}
</style>
</head>
<body>
<!--小球-->
<div class="swapper">
</div>
<script>
var oDiv = document.getElementsByClassName('swapper')[0];
var timer = null;
oDiv.onclick = function(){
console.log("inter click");
startMove(this);
}
function startMove(dom){
clearInterval(dom.timer);
var iSpeedx = 6;
var iSpeedy = 8;
var g = 3
dom.timer = setInterval(function(){
iSpeedy += g;
var newTop = dom.offsetTop + iSpeedy;
var newLeft = dom.offsetLeft + iSpeedx;
if(newTop >= document.documentElement.clientHeight - dom.clientHeight){
iSpeedy *= -1;
iSpeedy *= 0.8;
iSpeedx *= 0.8;
newTop= document.documentElement.clientHeight - dom.clientHeight;
}
if(newTop <= 0){
iSpeedy *= -1;
iSpeedy *= 0.8;
iSpeedx *= 0.8;
newTop = 0;
}
if(newLeft >= document.documentElement.clientWidth - dom.clientWidth){
iSpeedx *= -1;
iSpeedy *= 0.8;
iSpeedx *= 0.8;
newLeft= document.documentElement.clientWidth - dom.clientWidth;
}
if(newLeft <= 0){
iSpeedx *= -1;
iSpeedy *= 0.8;
iSpeedx *= 0.8;
newLeft = 0;
}
if(Math.abs(iSpeedx) < 1){
iSpeedx = 0;
}
if(Math.abs(iSpeedy) < 1){
iSpeedy = 0;
}
if(iSpeedy == 0 && iSpeedx == 0){
clearInterval(dom.timer);
console.log("timer clear all");
}
dom.style.top = newTop + 'px';
dom.style.left = newLeft + 'px';
},30);
console.log("timer end");
}
</script>
</body>
</html>