前言
在读书的时候,学物理的时候有提到匀速运动。Js代码也可以实现匀速运动,你信不信?下面就来一个简单的匀速运动的代码实例。
匀速运动实例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box {
width: 100px;
height: 100px;
background-color: #009F95;
position: absolute;
left: 100px;
}
</style>
</head>
<body>
<div id="box"></div>
<button id="start">开始</button>
<script type="text/javascript">
var oStart = document.getElementById("start")
var oBox = document.getElementById("box")
var timer = null
oStart.onclick = function() {
clearInterval(timer)
timer = setInterval(function(){
var attrValue = parseInt(getStyle(oBox,"left"))+10
oBox.style.left = attrValue+"px"
// 添加一个目标点,在500的时候停下来
// 解决回退问题思路:让前面先把attrValue 设置成500
if(attrValue == 500){
clearInterval(timer)
}
},100)
}
function getStyle(obj, attr) {
return window.getComputedStyle ? window.getComputedStyle(obj)[attr] : obj.currentStyle[attr]
}
</script>
</body>
</html>
匀速运动函数封装
/**
* 功能:做匀速运动
* @param {Object} obj 需要运动的对象
* @param {Object} step 步长
* @param {Object} target 停止的目标点
* @param {Object} direction 移动的方向,支持left和top
* @param {Object} speed 运动的频率
* @param {Object} callback 回调函数
*/
function move(obj, step, target, direction, speed, callback) {
// 给spped默认值
var spped = spped || 100
// 第一次清除 undefined 不会报错
clearInterval(obj.timer)
obj.timer = setInterval(function() {
var attrValue = parseInt(getStyle(obj, direction)) + step
if((step > 0 && attrValue > target) || (step < 0 && attrValue < target)) {
attrValue = target
}
obj.style[direction] = attrValue + "px"
if(attrValue == target) {
clearInterval(obj.timer)
console.log(callback)
// 如果运行完成,需要做一些操作,callback函数是等到运行结束以后,再执行
callback && callback()
}
}, speed)
}
匀速运动的简单应用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
li{
list-style: none;
width: 50px;
height: 50px;
background-color: #009F95;
position: absolute;
}
</style>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
// js文件是应用上面函数封装的方法,小伙伴们可以封装自己的tool.js
<script type="text/javascript" src="../js/tool.js" ></script>
<script type="text/javascript">
// 需求:移入li做匀速运动
var aLi = document.getElementsByTagName("li")
for (var i = 0; i < aLi.length; i++) {
aLi[i].style.top = i * 60+"px"
aLi[i].onmouseover = function(){
var This = this
move(this,10,500,"left",10,function(){
move(This,-10,0,"left",10)
})
}
}
</script>
</body>
</html>