我正在尝试制作一个按钮控制的动画,其中一个小棒图移动到右侧或左侧,具体取决于单击哪个按钮。
<!DOCTYPE html>
<html>
<style>
#stage{
width: 100px;
height: 100px;
position: relative;
border-style: dashed;
border-color: gray;
border-width: medium;
}
#actor{
width: 13px;
height: 15px;
position: absolute;
left: 0;
top: 0;
background-image: url("E:/Website Projects/man.PNG");
-webkit-transition: all 2s ease-out 0s;
-moz-transition: all 2s ease-out 0s;
transition: all 2s ease-out 0s;
}
</style>
<body>
<div id="stage">
<div id="actor"></div>
</div>
<div>
<button class="control" id="top">TOP</button> <br>
<button class="control" id="left">LEFT</button> <button class="control" id="right">RIGHT</button> <br>
<button class="control" id="down">DOWN</button>
</div>
</body>
<script>
var maxWidth = 100;
var maxHeight = 100;
var top = document.querySelector("#top");
var left = document.querySelector("#left");
var right = document.querySelector("#right");
var down = document.querySelector("#down");
top.addEventListener("click",moveTop,false);
left.addEventListener("click",moveLeft,false);
right.addEventListener("click",moveRight,false);
down.addEventListener("click",moveDown,false);
function moveTop(){
var actor = document.querySelector("#actor");
actor.style.top -= "25px";
}
function moveDown(){
var actor = document.querySelector("#actor");
actor.style.top += "25px";
}
function moveRight(){
var actor = document.querySelector("#actor");
actor.style.left += "25px";
}
function moveLeft(){
var actor = document.querySelector("#actor");
actor.style.left -= "25px";
}
</script>
</html>
答案 0 :(得分:3)
您无法将25px
添加到25px
作为字符串。
您只能将+=
和-=
用于整数。
您希望您的功能如下所示:
function moveDown(){
var actor = document.querySelector("#actor");
var num = parseInt(actor.style.top) || 0;
actor.style.top = num + 25 + "px";
}