通过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 相关文章推荐
Angularjs编写KindEditor,UEidtor,jQuery指令
Jan 28 Javascript
js将字符串中的每一个单词的首字母变为大写其余均为小写
Jan 05 Javascript
javascript监听页面刷新和页面关闭事件方法详解
Jan 09 Javascript
jquery+ajax实现省市区三级联动 (封装和不封装两种方式)
May 15 jQuery
浅谈Express异步进化史
Sep 09 Javascript
基于Vue过渡状态实例讲解
Sep 14 Javascript
vue路由嵌套的SPA实现步骤
Nov 06 Javascript
vue的diff算法知识点总结
Mar 29 Javascript
Angular6新特性之Angular Material
Dec 28 Javascript
VUE解决微信签名及SPA微信invalid signature问题(完美处理)
Mar 29 Javascript
使用 webpack 插件自动生成 vue 路由文件的方法
Aug 20 Javascript
一篇文章了解正则表达式的替换技巧
Feb 24 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
谈谈新手如何学习PHP
2006/12/14 PHP
php+jquery编码方面的一些心得(utf-8 gb2312)
2010/10/12 PHP
学习php设计模式 php实现状态模式
2015/12/07 PHP
PHP实现的简单分页类及用法示例
2016/05/06 PHP
php实现xml与json之间的相互转换功能实例
2016/07/07 PHP
PHP判断文件是否被引入的方法get_included_files用法示例
2016/11/29 PHP
php链式操作的实现方式分析
2019/08/12 PHP
php统计数组不同元素的个数的实例方法
2019/09/26 PHP
js脚本学习 比较实用的基础
2006/09/07 Javascript
ASP Json Parser修正版
2009/12/06 Javascript
返回对象在当前级别中是第几个元素的实现代码
2011/01/20 Javascript
去掉gridPanel表头全选框的小例子
2013/07/18 Javascript
用js替换除数字与逗号以外的所有字符的代码
2014/06/07 Javascript
JavaScript获取两个数组交集的方法
2015/06/09 Javascript
JS基于Mootools实现的个性菜单效果代码
2015/10/21 Javascript
js实现canvas图片与img图片的相互转换的示例
2017/08/31 Javascript
Spring Boot/VUE中路由传递参数的实现代码
2018/03/02 Javascript
原生JavaScript实现todolist功能
2018/03/02 Javascript
JavaScript常见继承模式实例小结
2019/01/11 Javascript
Postman动态获取返回值过程详解
2020/06/30 Javascript
[47:21]Liquid vs TNC Supermajor 胜者组 BO3 第一场 6.4
2018/06/05 DOTA
python利用datetime模块计算时间差
2015/08/04 Python
基于Python中求和函数sum的用法详解
2018/06/28 Python
对pytorch网络层结构的数组化详解
2018/12/08 Python
新年快乐! python实现绚烂的烟花绽放效果
2019/01/30 Python
Python树莓派学习笔记之UDP传输视频帧操作详解
2019/11/15 Python
关于Flask项目无法使用公网IP访问的解决方式
2019/11/19 Python
完美解决Django2.0中models下的ForeignKey()问题
2020/05/19 Python
Django框架请求生命周期实现原理
2020/11/13 Python
HTML5 Web缓存和运用程序缓存(cookie,session)
2018/01/11 HTML / CSS
Html5导航栏吸顶方案原理与对比实现
2020/06/10 HTML / CSS
总务岗位职责
2013/11/19 职场文书
教师开学感言
2014/02/14 职场文书
个人学习党的群众路线教育实践活动心得体会
2014/11/05 职场文书
先进集体事迹材料范文
2014/12/25 职场文书
入党积极分子培养人意见
2015/06/02 职场文书