2个回答
展开全部
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
body{ margin:0;}
#div{width:100px; height:100px; background:red; position:absolute; left:50px; bottom:0;}
</style>
<script>
window.onload=function ()
{
var oUp=document.getElementById('up');
var oDown=document.getElementById('down');
var oLeft=document.getElementById('left');
var oRight=document.getElementById('right');
var oDiv=document.getElementById('div');
var timer=null;
oUp.onmousedown=function ()
{
Move('top');
}
oDown.onmousedown=function ()
{
Move('bottom');
}
oLeft.onmousedown=function ()
{
Move('left');
}
oRight.onmousedown=function ()
{
Move('仿搭拦right');
}
var iSpeed=2;//每次移动的距离,可调整
var MoveTime=20;//移动间隔时间,可调备胡整
function Move (f)
{
clearInterval(timer);
timer=setInterval(function (){
switch (f)
{
case 'left' :
oDiv.style.left=oDiv.offsetLeft-iSpeed+'px';
break;
case 'right' :
oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';
break;
case 'top' :
oDiv.style.top=oDiv.offsetTop-iSpeed+'px';
break;
case 'bottom' :
oDiv.style.top=oDiv.offsetTop+iSpeed+'px';
}
},MoveTime)
}
oUp.onmouseup=oDown.onmouseup=oLeft.onmouseup=oRight.onmouseup=function ()
{
MouseUp ();
}
function MouseUp ()
{
clearInterval(timer);
}
}
</script>
</head>
<body>
<input type="button" value="向上" id="up">
<input type="button" value="向下" id="down">
<input type="button" value="向左" id="left">
<input type="button" value="向枝消右" id="right">
<div id="div"></div>
</body>
</html>
一个比较简单的按钮控制Div的上下左右移动
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询