网络技术
当前位置 :首页信息技术网络技术

JS获取鼠标位置的不同版本代码

来源: 作者: 时间:2010-06-06 点击:

一、

var mousePos;
function mousePosition(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop};
}
//显示出一个层,divId:层id;x:右偏移像素;y:下偏移像素;
function openDiv(divId,x,y){
if(x==null){x=0;}
if(y==null){y=0;}
if(document.getElementById(divId)!=null){
var dvs=document.getElementById(divId).style;
dvs.left=mousePos.x+x+"px";
dvs.top=mousePos.y+y+"px";
dvs.display="";}
}
function mouseMove(ev){
ev = ev || window.event;
mousePos = mousePosition(ev);
}
window.document.onmousemove = mouseMove;

二、

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>JS获得鼠标位置(兼容多浏览器ie,firefox)脚本之家修正版</title>
</head>

<body>

<script>
function mouseMove(ev)
{
ev= ev || window.event;
var mousePos = mouseCoords(ev);
//alert(ev.pageX);
document.getElementById("xxx").value = mousePos.x;
document.getElementById("yyy").value = mousePos.y;
}

function mouseCoords(ev)
{
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}

document.onmousemove = mouseMove;
</script>
鼠标 X 轴:
<input id=xxx type=text>

鼠标 Y 轴:
<input id=yyy type=text>
</body>

三、

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;
}

 

四、

<title>Js获取适时获取鼠标坐标值并显示</title>
<script type="text/javascript">
var getCoordInDocumentExample = function(){
var coords = document.getElementById("coords");
coords.onmousemove = function(e){
var pointer = getCoordInDocument(e);
var coord = document.getElementById("coord");
coord.innerHTML = "X,Y=("+pointer.x+", "+pointer.y+")";
}
}
var getCoordInDocument = function(e) {
e = e || window.event;
var x = e.pageX || (e.clientX +
(document.documentElement.scrollLeft
|| document.body.scrollLeft));
var y= e.pageY || (e.clientY +
(document.documentElement.scrollTop
|| document.body.scrollTop));
return {'x':x,'y':y};
}
window.onload = function(){
getCoordInDocumentExample();
};
</script>
<div id="coords" style="width:500px;height:200px;background:#F2F1D7;border:2px solid #0066cc;">
请在此移动鼠标。
</div>
<br />
<div id="coord" style="width:500px;border:2px solid #336699;">&nbsp;</div>

最新评论共有 位网友发表了评论
发表评论
用户名: 密码: 游客发言不需要密码