日期:2014-05-16  浏览次数:20437 次

传智博客js 学习笔记(3)图片随鼠标走

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
?<script type="text/javascript">
???? function MMove(){
????? var x=window.event.clientX;
??? var y=window.event.clientY;
??? var img=document.getElementById("img");
??? //alert(img.width);
?? // alert(img.style.top+"-"+img.style.left);
?? img.style.top=y+"px";
?? img.style.left=x+"px";
? }
? document.onmousemove=MMove;
?</script>
</head>

<body>
<img src="image/pic.JPG" alt="" id="img" style="position:absolute;top:100px;left:100px;" />
</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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
?<style type="text/css">
?? img{
?? position:absolute;
?? top:100px;
?? left:100px;
?? }
?</style>
?<script type="text/javascript">
???? function MMove(){
????? var x=window.event.clientX;
??? var y=window.event.clientY;
??? var img=document.getElementById("img");
??? //alert(img.width);
?? // alert(img.style.top+"-"+img.style.left);
?? img.style.top=y+"px";
?? img.style.left=x+"px";
? }
? document.onmousemove=MMove;
?</script>
</head>

<body>
<img src="image/pic.JPG" alt="" id="img" />


</body>
</html>

?

?

?

上面做法通不过,但是修改一下就OK

可以用class样式去定义,然后通过Dom方法获取

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
?<style type="text/css">
?? .img{
?? position:absolute;
?? top:100px;
?? left:100px;
?? }
?</style>
?<script type="text/javascript">
???? function MMove(){
????? var x=window.event.clientX;
??? var y=window.event.clientY;
??? var img=document.getElementsByClassName("img");
?? img[0].style.top=y+"px";
?? img[0].style.left=x+"px";//注意这里是img[0]代表是class=‘img’的第一张图片

? }
? document.onmousemove=MMove;
?</script>
</head>

<body>

<img src="image/pic.JPG" alt="" class="img" />

</body>
</html>