我最终的目的是用源生JS代码封装一个domove()函数,可以在传参之后实现元素任意方向的运动,在达到最终目的前应该一步一步地完成:
1.配合之前封装过的getstyle()函数,实现点击按钮之后让一个div向前移动10px的效果:
<body>
<button id="btn">前进</button>
<div id="div1" style="width:100px; height:100px; background:red; margin-top:20px; position:absolute;"></div>
<script>
var oBtn=document.getElementById("btn");
var oDiv=document.getElementById("div1");
function getstyle(obj,attr){
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
}
oBtn.onclick=function(){
var nowPosition =parseInt(getstyle(oDiv,'left'));
oDiv.style.left=nowPosition+10+'px';
}
</script>
</body>
2.用两个按钮分别控制div向前向后动
3.把div向前向后动改成上下左右移动
·
·
·
按照这样的思路,再结合计时器,最终一步步实现一点按钮就能使元素连贯地变到目的的样式:
function doMove(id,derection,speed,subjectPosition){
//id:要运动的元素;derection:以什么方向为参照来运动(left、right、top、bottom);speed:计时器每循环一次移动的距离;subjectPosition:运动所要达到的样式的值
speed= parseInt(getstyle(getid(id),derection))> subjectPosition? -speed : speed;//判断运动的方向
clearInterval(getid(id).timer);
getid(id).timer=setInterval(function(){
var nowPosition =parseInt(getstyle(getid(id),derection));
var thisPosition=nowPosition+speed;
if(thisPosition>=subjectPosition&&speed>0||thisPosition<=subjectPosition&&speed<0){
//判断有无达到目标点
thisPosition=subjectPosition;
clearInterval(getid(id).timer);
}
getid(id).style[derection]=thisPosition+'px';
},30)
}
例如:模拟一些网页,做一个“点击有惊喜”的效果。
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
#div1{
width:800px; height:800px; background:#000; position:relative;left:50%; margin-left:-400px;}
#div2{
width:30px; height:200px; background:#666; color:#fff;text-align:center; padding-top:50px; position:absolute; right:0; top:40%; cursor:pointer;}
#div3{
width:80px; height:200px; background:#69F; color:#909;text-align:center; padding-top:50px; position:absolute; right:-80