通过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 自动播放的实例代码
Nov 19 Javascript
分享20款美化网站的 jQuery Lightbox 灯箱插件
Oct 10 Javascript
Immutable 在 JavaScript 中的应用
May 02 Javascript
Jquery插件仿百度搜索关键字自动匹配功能
May 11 Javascript
easyui window refresh 刷新两次的解决方法(推荐)
May 18 Javascript
JS IOS/iPhone的Safari浏览器不兼容Javascript中的Date()问题如何解决
Nov 11 Javascript
angular+webpack2实战例子
May 23 Javascript
基于jquery日历价格、库存等设置插件
Jul 05 jQuery
js es6系列教程 - 基于new.target属性与es5改造es6的类语法
Sep 02 Javascript
vue-cli3项目展示本地Markdown文件的方法
Jun 07 Javascript
浅谈VUE中演示v-for为什么要加key
Jan 16 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
后宫无数却洁身自好的男主,唐三只爱小舞
2020/03/02 国漫
php绘制一个矩形的方法
2015/01/24 PHP
WordPress开发中用于标题显示的相关函数使用解析
2016/01/07 PHP
phalcon框架使用指南
2016/02/23 PHP
javascript 函数式编程
2007/08/16 Javascript
用js实现的检测浏览器和系统的函数
2009/04/09 Javascript
JavaScript读取中文cookie时的乱码问题的解决方法
2009/10/14 Javascript
javascript特殊用法示例介绍
2013/11/29 Javascript
一个html5播放视频的video控件只支持android的默认格式mp4和3gp
2014/05/08 Javascript
jquery delay()介绍及使用指南
2014/09/02 Javascript
JQuery判断checkbox是否选中及其它复选框操作方法合集
2015/06/01 Javascript
JavaScript控制浏览器全屏及各种浏览器全屏模式的方法、属性和事件
2015/12/20 Javascript
非常实用的js验证框架实现源码 附原理方法
2016/06/08 Javascript
AngularJs  Understanding Angular Templates
2016/09/02 Javascript
原生JS取代一些JQuery方法的简单实现
2016/09/20 Javascript
JavaScript 数据类型详解
2017/03/13 Javascript
详解AngularJS脏检查机制及$timeout的妙用
2017/06/19 Javascript
javascript 日期相减-在线教程(附代码)
2017/08/17 Javascript
vue使用自定义事件的表单输入组件用法详解【日期组件与货币组件】
2020/06/01 Javascript
jQuery实现异步上传一个或多个文件
2020/08/17 jQuery
详解Node.JS模块 process
2020/08/31 Javascript
如何在现代JavaScript中编写异步任务
2021/01/31 Javascript
[03:40]DOTA2亚洲邀请赛小组赛第二日 赛事回顾
2015/01/31 DOTA
[01:07:53]RNG vs VG 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
Python快速查找list中相同部分的方法
2018/06/27 Python
Python3 SSH远程连接服务器的方法示例
2018/12/29 Python
OpenCV python sklearn随机超参数搜索的实现
2020/01/17 Python
解决pycharm中opencv-python导入cv2后无法自动补全的问题(不用作任何文件上的修改)
2020/03/05 Python
Python figure参数及subplot子图绘制代码
2020/04/18 Python
详细分析Python垃圾回收机制
2020/07/01 Python
记一次django内存异常排查及解决方法
2020/08/07 Python
英国现代家具和装饰网站:PN Home
2018/08/16 全球购物
linux面试题参考答案(8)
2015/08/11 面试题
大专应届毕业生求职信
2014/07/15 职场文书
工程项目经理岗位职责
2015/02/02 职场文书
如何使用vue3打造一个物料库
2021/05/08 Vue.js