JavaScript 鼠标事件

来源:互联网 发布:网络电视30天回看 编辑:程序博客网 时间:2024/05/29 14:12

鼠标位置
可视区位置:clientX、clientY
例子1:跟随鼠标的Div

跟随鼠标移动的Div

<!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><style>#div1 {width:100px; height:100px; background:red; position:absolute;}</style><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script>document.onmousemove=function (ev){    var oEvent=ev||event;    var oDiv=document.getElementById('div1');    var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;    var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft;    oDiv.style.left=oEvent.clientX+scrollLeft+'px';    oDiv.style.top=oEvent.clientY+scrollTop+'px';};</script></head><body style="height:2000px;"><div id="div1"></div></body></html>

消除滚动条的影响
滚动条的意义——可视区与页面顶部的距离
获取鼠标在页面的绝对位置
封装函数
例子2:一串跟随鼠标的Div
一串跟随鼠标的div

<!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><style>div {width:10px; height:10px; background:red; position:absolute;}</style><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script>window.onload=function (){    var aDiv=document.getElementsByTagName('div');    var i=0;    document.onmousemove=function (ev)    {        var oEvent=ev||event;        for(i=aDiv.length-1;i>0;i--)        {            aDiv[i].style.left=aDiv[i-1].style.left;            aDiv[i].style.top=aDiv[i-1].style.top;        }        aDiv[0].style.left=oEvent.clientX+'px';        aDiv[0].style.top=oEvent.clientY+'px';    };};</script></head><body><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></body></html>

参考:JavaScript

原创粉丝点击