新手初学
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
button{
width:100px;
height:50px;
background:#dddddd;
}
div{
width: 200px;
height:200px;
background: deepskyblue;
position: relative;
z-index: -1;
}
</style>
</head>
<body>
<button id="btn0">Up</button>
<button id="btn1">Down</button>
<button id="btn2">Left</button>
<button id="btn3">Right</button>
<div id="div0"></div>
<script>
var div=document.getElementById("div0");
div.lefts=0;
div.tops=0;
var step=50;
for(var i=0;i<4;i++){
var btn=document.getElementById("btn"+i);
btn.addEventListener("click",function () {
clickHandler(this);
});
}
function clickHandler(e) {
switch (e.innerHTML){
case "Down":
tops(div);
break;
case "Up":
bottoms(div);
break;
case "Right":
lefts(div);
break;
case "Left":
rights(div);
break;
default :
console.log("错误");
}
}
function lefts(_div) {
_div.lefts+=step;
_div.style.left=_div.lefts+"px";
}
function rights(_div) {
_div.lefts-=step;
_div.style.left=_div.lefts+"px";
}
function tops(_div) {
_div.tops+=step;
_div.style.top=_div.tops+"px";
}
function bottoms(_div) {
_div.tops-=step;
_div.style.top=_div.tops+"px";
}
</script>
</body>
</html>