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

昨天写的脚本在获取鼠标位置的时候有些问题。在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>

(0)

相关推荐

  • javascript ie6兼容position:fixed实现思路

    positon:fixed 让HTML元素脱离文档流固定在浏览器的某个位置 网页中经常会有浮动的导航条会用到这种定位模式,但是ie6下并不兼容这种定位 浮动导航条的样式,重要的是position:fixed;bottom:60px;(浮动导航底部距离窗口底部60px) 复制代码 代码如下: .floating_9677{position:fixed; z-index:961; bottom:60px;} ie6下positon:fixed不起作用,只能靠js来实现了,首先在ie6下需要将posi

  • javascript contains和compareDocumentPosition 方法来确定是否HTML节点间的关系

    从那起,我已经对这些方法做了大量的研究,并且已经在很多场合使用他们.在很多任务中,他们被证明是非常有用的(特别关于结构的抽象 DOM 选择器). 1.DOMElement.contains(DOMNode) 这个方法起先用在 IE ,用来确定 DOM Node 是否包含在另一个 DOM Element 中. 当尝试优化 CSS 选择器遍历(像:"#id1 #id2"),这个方法很有用.你可以通过 getElementById 得到元素,然后使用 .contains() 确定 #id1

  • javascript改变position值实现菜单滚动至顶部后固定

    现在很多网站都有这样的一个效果,当页面滚动到一定高度时,菜单栏会固定在页面顶部.其实就是改变 position 的值. html 代码: 复制代码 代码如下: <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" t

  • JS中定位 position 的使用实例代码

    废话不多说了,直接给大家贴代码了,具体代码如下所述: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> img{width:200px;} </style> </head> <body> <div id=&q

  • IE6中使用position导致页面变形的解决方案(js代码)

    如图所示: 解决方案: 1.缩放窗体时先得到内容左边的空白宽度. $("#nav").offset().left; 得到内容区左边的空白宽度. 2.得到整个窗体的宽度(注意:桌面分辨率为基准,少了加上来). 3.用桌面分辨率的宽度-页面内容区的宽度/2,就可以得到一边多余的宽度. 4.如果得到的值跟$("#nav").offset().left;得到值不同,则可以调到两值相同. 复制代码 代码如下: var ietest=function() { if ($.bro

  • js完美解决IE6不支持position:fixed的bug

    先来看段代码 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>IE6 position:fixed bug</title> <style> *{padding:0;margin:0} p{height:2000px} #

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

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

  • 浅析JS获取url中的参数实例代码

    js获取url中的参数代码如下所示,代码简单易懂,附有注释,写的不好还请见谅! function UrlSearch() { var name, value; var str = location.href; //取得整个地址栏 var num = str.indexOf("?") str = str.substr(num + 1); //取得所有参数 stringvar.substr(start [, length ] var arr = str.split("&&

  • js 获取范围内的随机数实例代码

    实例如下: function RandomNum(Min,Max){ var Range = Max - Min; var Rand = Math.random(); var num = Min + Math.round(Rand * Range); return num; } RandomNum(10,20); 以上这篇js 获取范围内的随机数实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • js 获取当前select元素值的代码

    1.如果 select 元素下的所有 option 元素均没有指定 selected 属性,会默认选中第一个. 2.可以通过 select.selectedIndex 获取到选中的 option 元素的索引. 3.可以通过 select.options[select.selectedIndex] 获取到选中的 option 元素. 4.option 元素 <option selected="selected" value="value3">text3&l

  • jQuery(js)获取文字宽度(显示长度)示例代码

    今天遇到了获取文字宽度的问题,查了很久,终于在一个国外网站上找到了方法,但是不能直接使用,于是修改了一下,成功使用到了项目中,在这里分享给大家. 首先在body标签最后添加一个子标签: 复制代码 代码如下: <span id="ruler">test</span> 然后添加相应的css代码: 复制代码 代码如下: #ruler { visibility: hidden; white-space: nowrap; font-size: 24px; } 接下来直接在

  • js获取 gif 的帧数的代码实例

    使用 javascript 获取 GIF 图的帧数,如果帧数过大,则不让传到服务器 这里是使用一个插件: github地址为: https://github.com/buzzfeed/libgif-js <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <meta name="viewport" con

  • js获取指定日期前后的日期代码

    复制代码 代码如下: function getmonths(dateday){ /*获取当前日期的月份*/ var curDate = new Date(dateday); return curDate.getMonth()+1; }; function getYears(dateday){ /*获取当前日期的年份*/ var curDate = new Date(dateday); return curDate.getFullYear(); }; function getCountDays(d

  • js 获取Listbox选择的值的代码

    复制代码 代码如下: <script type="text/javascript"> function GetValue() { var strlist = document.getElementById("ListBox1");//获取Listbox var str= ""; //遍历Listbox,取得选中项的值 if (strlist.options.length > 0) { for (var i = 0; i <

  • php/js获取客户端mac地址的实现代码

    废话不多讲,直接上代码吧! 复制代码 代码如下: <?php   class MacAddr {       public $returnArray = array();        public $macAddr; function __contruct($os_type=null){         if(is_null($os_type)) $os_type = PHP_OS;           switch (strtolower($os_type)){           case

随机推荐