在测试用鼠标点击按钮,使图片左右上下移动:
效果如下:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
div{
width: 600px;
height: 400px;
margin: 100px auto 0;
background: pink;
position: relative;
}
img{
width: 60px;
height: 60px;
position: absolute;
top: 0px;
left: 0px;
}
table{
width: 120px;
height: 120px;
margin: 0 auto;
}
</style>
<script>
function move(num){
var mario = document.getElementById("mario");
var l = mario.style.left;//获取图片当前left值
var t = mario.style.top;//获取图片当前top值
l = Number(l.substr(0, l.length-2));//截取left值,去掉px 如果改成parseInt()则会失效,详情继续往下看解决办法
t = Number(t.substr(0, t.length-2));//截取top值,去掉px
switch(num){
case 0:
mario.style.top = (t-10)+"px";
break;
case 1:
mario.style.left = (l+10)+"px";
break;
case 2:
mario.style.top = (t+10)+"px";
break;
case 3:
mario.style.left = (l-10)+"px";
break;
}
}
</script>
</head>
<body>
<div>
<img src="img.jpg" id="mario" alt=""/>
</div>
<table>
<tr>
<th colspan="3">点击移动图片</th>
</tr>
<tr align="center">
<td colspan="3"><input type="button" value="↑" onclick="move(0)"></td>
</tr>
<tr>
<td><input type="button" value="←" onclick="move(3)"></td>
<td>㊣</td>
<td><button onclick="move(1)">→</button></td>
</tr>
<tr align="center">
<td colspan="3"><input type="button" value="↓" onclick="move(2)"></td>
</tr>
</table> </body>
</html>
在上面如果我们吧Number()改成parseInt() 我们会发现失效了,鼠标点击图片不会移动,反而会报错。
如果我们想换成parseInt()那我们可以这样改
把img图形的样式改为内联样式:
<img src="img.jpg" id="mario" alt="" style="position: absolute;top: 0px;left: 0px;"/>
这样再把l = Number(l.substr(0, l.length-2)); 改为l = parseInt(l.substr(0, l.length-2));就不会报错了
为什么会这样呢:
是因为style只能获取内联样式,所以使用parseInt就不能实现。 键盘控制图片移动:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
div{
width: 600px;
height: 400px;
margin: 100px auto 0;
background: pink;
position: relative;
}
img{
width: 60px;
height: 60px;
position: absolute;
top: 0px;
left: 0px;
}
table{
width: 120px;
height: 120px;
margin: 0 auto;
}
</style>
<script>
window.onload = function () {
document.onkeydown = function () {
var event = event || window.event;//浏览器兼容问题
var mario = document.getElementById("mario");
var l = mario.style.left;//获取图片当前left值
var t = mario.style.top;//获取图片当前top值
l = Number(l.substr(0, l.length-2));//截取left值,去掉px
t = Number(t.substr(0, t.length-2));//截取top值,去掉px
switch(event.keyCode){
case 38:
mario.style.top = (t-10)+"px";
break;
case 39:
mario.style.left = (l+10)+"px";
break;
case 40:
mario.style.top = (t+10)+"px";
break;
case 37:
mario.style.left = (l-10)+"px";
break;
}
}
}
function move(num){ }
</script>
</head>
<body>
<div>
<img src="img.jpg" id="mario" alt=""/>
</div> </body>
</html>