通过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 相关文章推荐
如何让动态插入的javascript脚本代码跑起来。
Jan 09 Javascript
JSONP 跨域访问代理API-yahooapis实现代码
Dec 02 Javascript
Javascript 鼠标移动上去小三角形滑块缓慢跟随效果
Apr 26 Javascript
javascript常用方法汇总
Dec 02 Javascript
jQuery实现form表单元素序列化为json对象的方法
Dec 09 Javascript
纯JS实现轮播图
Feb 22 Javascript
js 实现复选框只能选择一项的示例代码
Jan 23 Javascript
vue获取form表单的值示例
Oct 29 Javascript
vue+webpack dev本地调试全局样式引用失效的解决方案
Nov 12 Javascript
微信小程序商品详情页底部弹出框
Nov 22 Javascript
vue实现列表滚动的过渡动画
Jun 29 Javascript
如何用JavaScript学习算法复杂度
Apr 30 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面向对象中static静态属性与方法的内存位置分析
2015/02/08 PHP
PHP实现简单ajax Loading加载功能示例
2016/12/28 PHP
php查询内存信息操作示例
2019/05/09 PHP
laravel-admin表单提交隐藏一些数据,回调时获取数据的方法
2019/10/08 PHP
Laravel手动返回错误码示例
2019/10/22 PHP
php数值计算num类简单操作示例
2020/05/15 PHP
filemanage功能中用到的lib.js
2007/04/08 Javascript
jquery 根据name名获取元素的value值
2015/02/27 Javascript
js实现的星星评分功能函数
2015/12/09 Javascript
ES6中的箭头函数实例详解
2017/04/06 Javascript
Vue2.0表单校验组件vee-validate的使用详解
2017/05/02 Javascript
关于Angular2 + node接口调试的解决方案
2017/05/28 Javascript
BootStrap Table复选框默认选中功能的实现代码(从数据库获取到对应的状态进行判断是否为选中状态)
2017/07/11 Javascript
Node.js使用Express.Router的方法
2017/11/14 Javascript
Bootstrap treeview实现动态加载数据并添加快捷搜索功能
2018/01/07 Javascript
使用D3.js+Vue实现一个简单的柱形图
2018/08/05 Javascript
mpvue中使用flyjs全局拦截的实现代码
2018/09/13 Javascript
Three.js实现3D机房效果
2018/12/30 Javascript
JavaScript语句错误throw、try及catch实例解析
2020/08/18 Javascript
浅谈python类属性的访问、设置和删除方法
2016/07/25 Python
Python批量查询域名是否被注册过
2017/06/21 Python
Django后台获取前端post上传的文件方法
2018/05/28 Python
APIStar:一个专为Python3设计的API框架
2018/09/26 Python
在Python中分别打印列表中的每一个元素方法
2018/11/07 Python
Python3内置模块pprint让打印比print更美观详解
2019/06/02 Python
python 和c++实现旋转矩阵到欧拉角的变换方式
2019/12/04 Python
python实现tail实时查看服务器日志示例
2019/12/24 Python
Centos7下源码安装Python3 及shell 脚本自动安装Python3的教程
2020/03/07 Python
优衣库英国官网:UNIQLO英国
2016/12/25 全球购物
Europcar比利时:租车
2019/08/26 全球购物
Groupon荷兰官方网站:高达70%的折扣
2019/11/01 全球购物
幼师岗位求职简历的自荐信格式
2013/09/21 职场文书
群众路线教育实践活动的心得体会
2014/09/03 职场文书
单位推荐信范文
2015/03/27 职场文书
感恩教育主题班会
2015/08/12 职场文书
MySQL数字类型自增的坑
2021/05/07 MySQL