通过JS 获取Mouse Position(鼠标坐标)的代码


Posted in Javascript onSeptember 21, 2009

昨天写的脚本在获取鼠标位置的时候有些问题。在IE中始终当有滚动条的时候,发现document.body.scrollTop并没有起到作用。
后来在google中搜索到一篇文章Mouse Cursor Position,详细介绍了浏览器鼠标定位的问题。各个浏览器对鼠标定位的标准不一样,就连不通版本的ie对定位支持都不一样。
document.body.scrollLeft,document.body.scrollTop只用于IE6以前的版本,在IE6中,对没有宣告 DOCTYPE,或者宣告的是transitional DOCTYPE,那么IE6将使用document.documentElement.scrollLeft 来获取鼠标的绝对位置。

Stephen Chapman提供的函数做个记录

function mouseX(evt) {
if (evt.pageX) return evt.pageX;
else if (evt.clientX)
  
return evt.clientX + (document.documentElement.scrollLeft ?
  
document.documentElement.scrollLeft :
  
document.body.scrollLeft);
else return null;
}
function mouseY(evt) {
if (evt.pageY) return evt.pageY;
else if (evt.clientY)
  
return evt.clientY + (document.documentElement.scrollTop ?
  
document.documentElement.scrollTop :
  
document.body.scrollTop);
else return null;
}
Mouse Cursor Position
Join the Discussion
Questions? Comments?
Until recently there was no standard way of determining the position of the mouse cursor within the browser. The W3C standards say that the current mouse cursor position within the browser window when an event is triggered should be given by event.clientX and event.clientY to obtain the distance from the left and top of the browser window respectively.
I have tested this in a number of different browsers and have found that Internet Explorer 6, Netscape 6+, Firefox, and Opera 7+ all produce correct values for the mouse coordinates relative to the browser window in these fields. To obtain the position within the web page you would simply add the scroll position of the page within the browser window.
Opera 5 and 6 produced values for these fields but the values are relative to the top of the web page instead of relative to the browser window and so adding the scroll position would produce a wrong result with these browsers. Netscape 4 doesn't understand these fields at all and so would give an error if this code were used by itself.
One added complication is that Internet Explorer uses two different ways to determine the scroll position of the page. It uses document.body.scrollLeft and document.body.scrollTop in versions before version 6 as well as in version 6 when there is no DOCTYPE declared or a transitional DOCTYPE is declared. When IE6 is declared using a strict DOCTYPE document.documentElement.scrollLeft and document.documentElenent.scrollTop are used instead. Other browsers either use one of these values or pageXOffset and pageYOffset.
Although not part of the W3C standards there is another pair of fields that will give the position of the mouse cursor that is useful. With the exception of Internet Explorer and Opera 5 and 6, all of the browsers I have mentioned also support event.pageX and event.pageY which give the mouse cursor position relative to the top left corner of the web page itself. Using these fields you do not have to add the scroll position of the page.
By combining tests for both of these methods together we can create code to locate the mouse cursor position that will work on Internet Explorer, Netscape 4+, Firefox, and Opera 7+. You just need to pass the event to the following functions to retrieve the appropriate position on the web page.
function mouseX(evt) {
if (evt.pageX) return evt.pageX;
else if (evt.clientX)
return evt.clientX + (document.documentElement.scrollLeft ?
document.documentElement.scrollLeft :
document.body.scrollLeft);
else return null;
}
function mouseY(evt) {
if (evt.pageY) return evt.pageY;
else if (evt.clientY)
return evt.clientY + (document.documentElement.scrollTop ?
document.documentElement.scrollTop :
document.body.scrollTop);
else return null;
}
There are a couple of other pairs of fields that give mouse cursor positions that are less useful. The fields event.screenX and event.screenY are defined in all of the browsers I tested. They give the position of the mouse cursor relative to the top left corner of the screen. Without knowing the position of the top left corner of the browser window this information is not very useful with respect to being able to interact with the web page.
The fields event.x and event.y also exist in Netscape 4, Internet Explorer, and Opera 7+. In Netscape 4 these fields give the position within the web page exactly the same as the pageX and pageY fields. In Internet Explorer and Opera 8 they give the position of the mouse cursor within the current object (if that object is positioned absolute, relative, or fixed) or within the page (for static objects). Opera 7 appears to use these fields to give the position of the mouse cursor relative to the bottom left corner of the screen.
还要其他的情况:
调用方法:
var pos=GetObjPos(ID); 
function CPos(x, y) 
{ 
this.x = x; 
this.y = y; 
} 
//获取控件的位置 
function GetObjPos(ATarget) 
{ 
var target = ATarget; 
var pos = new CPos(target.offsetLeft, target.offsetTop); 
var target = target.offsetParent; 
while (target) 
{ 
pos.x += target.offsetLeft; 
pos.y += target.offsetTop; 
target = target.offsetParent 
} 
return pos; 
}

下面是我自己开发项目中的实例:
<script type="text/jscript" language="jscript" > function showPopup(obj,evt) { 
var strDate = $(obj).attr('dateTime'); 
var strUserName = $(obj).attr('userName'); 
var id = "event_" + strDate.replace(/-/g, ''); 
var box = $('#'+id); 
if (box.length == 0) { 
$(document.body).append("<div id='" + id + "' class='popupinfo'></div>"); 
box = $('#' + id); 
box.css("position", "absolute"); 
box.css("display", "block"); 
box.css("z-index", "100"); 
box.append('<input id="File1" type="image" src="../Images/Onload.gif"/>'); 
Microsoft.PMWeb.WebSite.SiteService.GetEventInfoByDate(strUserName + "#" + strDate, onSuccess, onFailed, "1111"); 
} 
else { 
var imgLoad = box.find(":image"); 
imgLoad.css("display", "none"); 
} 
var objQueryPosition = GetObjPos(obj); 
box.css("left", mousePos.x); 
box.css("top", mousePos.y); 
box.css("display", ""); 
function onSuccess(result, context, methodName) { 
var imgLoad = box.find(":image"); 
imgLoad.css("display","none"); 
box.append(result); 
} 
function onFailed(error, context, methodName) { 
var errorMessage = error.get_message(); 
alert("Review Failed:" + errorMessage); 
} 
} 
function hidePopup(obj) { 
var strDate = $(obj).attr('dateTime'); 
var strUserName = $(obj).attr('userName'); 
var id = "event_" + strDate.replace(/-/g, ''); 
var box = $('#'+id); 
if (box.length != 0) { 
$('#'+id).css("display", "none"); 
} 
} 
var mousePos; 
function mouseMove(ev) { 
ev = ev || window.event; 
mousePos = mouseCoords(ev); 
} 
function mouseCoords(ev) { 
if (ev.pageX || ev.pageY) { 
return { x: ev.pageX, y: ev.pageY }; 
} 
return { 
x: ev.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft), 
y: ev.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) 
}; 
} 
document.onmousemove = mouseMove; 
</script>
Javascript 相关文章推荐
js调试工具 Javascript Debug Toolkit 2.0.0版本发布
Dec 02 Javascript
使用js获取QueryString的方法小结
Feb 28 Javascript
在Ajax中使用Flash实现跨域数据读取的实现方法
Dec 02 Javascript
原生js和jquery中有关透明度设置的相关问题
Jan 08 Javascript
json实现添加、遍历与删除属性的方法
Jun 17 Javascript
Windows环境下npm install 报错: operation not permitted, rename的解决方法
Sep 26 Javascript
RequireJS简易绘图程序开发
Oct 28 Javascript
Bootstrap导航条学习使用(一)
Feb 08 Javascript
关于jQuery库冲突的完美解决办法
May 20 jQuery
JavaScript变量提升和严格模式实例分析
Jan 27 Javascript
JavaScript原型式继承实现方法
Nov 06 Javascript
浅谈vue 锚点指令v-anchor的使用
Nov 13 Javascript
用jQuery技术实现Tab页界面之二
Sep 21 #Javascript
Tab页界面,用jQuery及Ajax技术实现
Sep 21 #Javascript
一个js写的日历(代码部分网摘)
Sep 20 #Javascript
下载站控制介绍字数显示的脚本 显示全部 隐藏介绍等功能
Sep 19 #Javascript
js表格分页实现代码
Sep 18 #Javascript
ext 同步和异步示例代码
Sep 18 #Javascript
JQuery的ajax基础上的超强GridView展示
Sep 18 #Javascript
You might like
如何限制访问者的ip(PHPBB的代码)
2006/10/09 PHP
一个漂亮的php验证码类(分享)
2013/08/06 PHP
php实现把url转换迅雷thunder资源下载地址的方法
2014/11/07 PHP
PHP使用CURL实现多线程抓取网页
2015/04/30 PHP
PHP第三方登录―QQ登录实现方法
2017/02/06 PHP
[原创]站长必须要知道的javascript广告代码
2007/05/30 Javascript
jQuery 获取对象 根据属性、内容匹配, 还有表单元素匹配
2010/05/31 Javascript
JavaScript内核之基本概念
2011/10/21 Javascript
js动态在form上插入enctype=multipart/form-data的问题
2012/05/24 Javascript
IE8中使用javascript动态加载CSS的解决方法
2014/06/17 Javascript
IE6-IE9中tbody的innerHTML不能赋值的解决方法
2014/09/26 Javascript
jQuery的文档处理程序详解
2016/05/10 Javascript
mvvm双向绑定机制的原理和实现代码(推荐)
2016/06/07 Javascript
举例讲解jQuery对DOM元素的向上遍历、向下遍历和水平遍历
2016/07/07 Javascript
XMLHttpRequest Level 2 使用指南
2016/08/26 Javascript
vuejs手把手教你写一个完整的购物车实例代码
2017/07/06 Javascript
详解vue移动端日期选择组件
2018/02/22 Javascript
解决vue-router中的query动态传参问题
2018/03/20 Javascript
在vue中v-bind使用三目运算符绑定class的实例
2018/09/29 Javascript
vue中多个倒计时实现代码实例
2019/03/27 Javascript
Nodejs监听日志文件的变化的过程解析
2019/08/04 NodeJs
编写Python脚本把sqlAlchemy对象转换成dict的教程
2015/05/29 Python
浅谈Python中带_的变量或函数命名
2017/12/04 Python
python re模块findall()函数实例解析
2018/01/19 Python
pyqt5与matplotlib的完美结合实例
2019/06/21 Python
Python 中的参数传递、返回值、浅拷贝、深拷贝
2019/06/25 Python
如何不用安装python就能在.NET里调用Python库
2019/07/12 Python
PyQt5实现暗黑风格的计时器
2019/07/29 Python
Python selenium页面加载慢超时的解决方案
2020/03/18 Python
Selenium webdriver添加cookie实现过程详解
2020/08/12 Python
python 将列表里的字典元素合并为一个字典实例
2020/09/01 Python
如何避免常见的6种HTML5错误用法
2017/11/06 HTML / CSS
暑期实践思想汇报
2014/01/06 职场文书
幼儿园教学管理制度
2014/02/04 职场文书
2014年社区国庆节活动方案
2014/09/16 职场文书
学术会议通知范文
2015/04/15 职场文书