.html代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>鼠标移动文字跟着移动</title>
<style type="text/css">
*{margin:0}
#layer{
width:100px;
height:30px;
position:relative;
float:left;
line-height:30px
}
</style>
<script type="text/javascript">
function move(){
var obj = document.getElementById('layer');
<span style="color:#ff0000;">obj.style.posLeft = event.x + 10 ;//将鼠标的X坐标当成控件的坐标
obj.style.posTop = event.y + 10;<span style="font-family: Arial, Helvetica, sans-serif;">//将鼠标的Y坐标当成控件的坐标</span></span>
}
<span style="color:#ff0000;">document.onmousemove = move;</span>
</script>
</head>
<body >
<div id="layer">我要动</div>
</body>
</html>
在浏览器中查看时,文字就可以随着鼠标移动 ,原理如注释所示,比较易懂。
按下键盘上下左右控制图像代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>鼠标移动文字跟着移动</title>
<style type="text/css">
*{margin:0}
#layer{
width:120px;
height:1200px;
position:relative;
float:left;
}
</style>
<script type="text/javascript">
function move(){
var obj = document.getElementById('layer');
if(event.keyCode == 39){
obj.style.posLeft =+ 10 ;
}
if(event.keyCode == 40){
obj.style.posTop =+ 10;
}
if(event.keyCode == 38){
obj.style.posDown =+ 10 ;
}
if(event.keyCode == 37){
obj.style.posRight =+10;
}
}
document.onkeydown = move;
</script>
</head>
<body >
<div id="layer"><img src="images/default.gif"/></div>
</body>
</html>