JavaScript中包含许多事件,每个事件都会触发相应的函数或程序,其中用得较多的就是鼠标事件,今天就教大家用鼠标事件来写一个鼠标跟随效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>无标题文档</title>
<style>
body{margin:0; padding:0} /* css部分 */
#to_top{
width:30px;
height:40px;
padding:20px;
font:14px/20px arial;
text-align:center;
background:#06c;
position:absolute;
cursor:pointer;
color:#fff
}
</style>
<script>
window.onload = function(){
var oTop = document.getElementById("to_top");
document.onmousemove = function(){
var oEvent =window.event; /* 事件的状态,即触发event对象的元素状态,例如鼠标,按键等 */
var scrollleft = document.documentElement.scrollLeft || document.body.scrollLeft; /* 获取元素当前相对网页左边缘内容的左偏移量 */
var scrolltop = document.documentElement.scrollTop || document.body.scrollTop; /* 获取元素当前相对网页上边缘内容的下偏移量 */
oTop.style.left = oEvent.clientX + scrollleft +20 +"px"; /* 调整跟随元素的位置 */
oTop.style.top = oEvent.clientY + scrolltop + 20 + "px";
}
}
</script>
</head>
<body style="height:1000px;">
<a href="#">文字</a>
<p id="to_top">鼠标跟随</p>
</body>
</html>