javascript基础练习-拖拽练习
程序员文章站
2024-02-26 18:53:28
...
效果图如下(先拖拽,后回放):
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height:auto;
background: rgba(255,165,0,0.6);
position:absolute;
top: 100px;
left: 500px;
color: white;
}
#box .content{
width: 100%;
height: auto;
padding: 10px;
}
#box .drag{
cursor: move;
width: auto;
background: orange;
height: 30px;
}
#box .play{
background: orange;
width: auto;
height: 30px;
line-height: 30px;
text-align: center;
color: white;
cursor: pointer;
}
</style>
<script type="text/javascript">
window.onload=function(argument){
var a=document.getElementById('box'),
b=a.getElementsByTagName('div'),
Drag,
arr=[],
X,
Y;
b[0].onmousedown=function(event){
Drag=true;
var event=event || window.event;
X=event.clientX-a.offsetLeft;
Y=event.clientY-a.offsetTop;
//将包含方块坐标信息的对象推入数组
arr.push({X:event.clientX-X,Y:event.clientY-Y});
};
document.onmousemove=function(event){
if (Drag) {
a.style.left=event.clientX-X+"px";
a.style.top=event.clientY-Y+"px";
b[1].innerHTML="left:"+a.offsetLeft+"<br/>"+"top:"+a.offsetTop;
arr.push({X:event.clientX-X,Y:event.clientY-Y});
}
};
document.onmouseup=function(){
Drag=false;
};
//点击回放,通过setInterval函数每隔一段时间抛出数组中存放的包含坐标信息的对象
b[2].onclick=function(){
if(arr.length>1){
var timer=setInterval(function(){
var popArr=arr.pop();
if (popArr) {
a.style.left=popArr.X+"px";
a.style.top=popArr.Y+"px";
b[1].innerHTML="left:"+a.offsetLeft+"<br/>"+"top:"+a.offsetTop;
}else{
clearInterval(timer);
}
},30);
}
};
b[1].innerHTML="left:"+a.offsetLeft+"<br/>"+"top:"+a.offsetTop;
}
</script>
</head>
<body>
<div id="box">
<div class="drag"></div>
<div class="content"></div>
<div class="play">回放</div>
</div>
</body>
</html>
上一篇: 听说,你的Loki还是单体?(下篇)
下一篇: Javascript 专项练习