把函数作为参数,调用的时候,先判断这个参数是不是存在,然后调用函数的时候加上()

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
*{margin:0px;padding:0px;}
div{width:100px;height:100px;background:red;position:absolute;top:60px;left:20px;}
input{width:100px;height:40px;}
</style>
<script>
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr]
}else{
return getComputedStyle(obj)[attr]
}
}

window.onload=function(){
var odiv=document.getElementsByTagName('div')[0];
var oinput=document.getElementsByTagName('input');
var time=null;
function doMove(obj,attr,target,speed,fn){
var cur=parseInt(getStyle(obj,attr))
speed=cur<target?Math.abs(speed):-Math.abs(speed);
clearInterval(obj.time);
obj.time=setInterval(function(){
cur+=speed;
if(cur>=target&&speed>0||cur<target&&speed<0){
clearInterval(obj.time);
if(fn){
fn()
}
cur=target;
}else{
odiv.style.left=cur+'px';
}
}) 
}


oinput[0].onclick=function(){
doMove(odiv,'left',500,10,function(){
alert('停1')
}) 

oinput[1].onclick=function (){
doMove(odiv,'left',0,10,function(){
alert('停2')
}) 
}


}
</script>
</head>
<body>
<div></div>
<input type="button" value="向右">
<input type="button" value="向左">
</body>
</html>

posted on 2017-11-24 10:24  luziluck  阅读(197)  评论(0编辑  收藏  举报

导航