<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>弹性运动</title>
<style type="text/css">
#div {
position: absolute;
left:25px;
bottom:30px;
width: 50px;
height: 50px;
background: blue;
border-radius: 50%;
}
#mat{
position: absolute;
left:0;
bottom:0;
width: 100px;
height: 30px;
background: brown;
position: absolute;
}
</style>
</head>
<body>
<script type="text/javascript">
//window.onload表示等页面标签内容加载完之后再加载window.onload里面的内容
window.onload = function(){
//分别设置div在x和y方向的的初速度
var speedX = 9;
var speedY = -50;
//获取div标签
var div = document.getElementById("div");
var mat = document.getElementById("mat");
//获取按钮
var btn = document.getElementById("btn");
//定义点击事件
mat.onclick = function(){
speedY = -50;
clearInterval(timer);
startMove();
};
//定义一个空的定时器,防止上次事件定时器的返回值叠加
var timer = null;
//定义点击事件函数
function startMove(){
//内部清空计时器,防止上次返回值叠加
clearInterval(timer);
//设置计时器
timer = setInterval(function(){
//竖直方向上反向运动时速度为负值,为了达到反弹逐渐速度逐渐减小的效果,可以在向下碰撞后速度加上一个正值
speedY += 7;
//获取div距离上边距的动态距离
var iH = div.offsetTop + speedY;
//获取div垂直方向运动的最大距离
var h = document.documentElement.clientHeight - div.offsetHeight - mat.offsetHeight;
if (iH >= h){
speedY = -speedY;
iH = h;
// speedX *= 0.95;
}else if(iH <= 0){
speedY = -speedY;
iH = 0;
}
//由于div.style.left和div.style.top还储存这上一次或第一次的计时后的值,此次计时后应把新的值储存起来,使div出现动态效果
div.style.top = iH + "px";
if(speedY===-2||speedY===-4){
return;
}
console.log(speedY);
},30);
}
}
</script>
<div id="mat"></div>//因为有window.onload在,等页面标签内容加载完之后再加载window.onload里面的内容,所以这两个元素可以放在最后面。如果没有window.onload,那么这两个div就要放在代码前面,否则获取对象是获取不到。