代码改变世界

DIV随鼠标滚动

2011-09-20 18:25  Carl Xing  阅读(967)  评论(0编辑  收藏  举报
<!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>
<title>JavaScript得到鼠标坐标</title>


<script language="javascript" type="text/javascript">
<!--
//这只是一种函数调用方法,当然也可以<body onmousemove="fun()">这样来调用
//用document.body.clientWidth;来获取浏览器宽度。
function document.onmousemove() {
var xx = document.getElementById("x");
var yy = document.getElementById("y");
var adiv = document.getElementById("adiv");
var al = document.getElementById("al");
xx.innerHTML
= "相对位置:X:" + window.event.x + " Y:" + window.event.y;
yy.innerHTML
= "绝对位置:X:" + window.event.screenX + " Y:" + window.event.screenY;


adiv.innerHTML
= "anchor的位置:X:" + al.getBoundingClientRect().right+" offsetWidth:"+al.offsetWidth;



var xy = document.getElementById("xy");
xy.style.top
= parseInt(window.event.y - 40) + "px";
xy.style.left
= parseInt(window.event.x - 20) + "px";
}
//-->
</script>


</head>
<body>
position属性非常重要。DIV的position属性设为relative随鼠标移动,absolute可设置绝对位置。
<div id="x">
x
</div>
<div id="y">
y
</div>
<div id="xy" style="position: relative; width: 50px; left: -100px;">
Follow_Me
</div>
<br />
<div>
<div id="al" style="width: 50px; left: 400px; position: absolute;">
<a href="#">anchor</a>
</div>
</div>
<div id="adiv">
</div>
</body>
</html>