JS 获取屏幕中鼠标的坐标值
先看下这段代码:<html><head><scriptlanguage="javascript">functionxy(){x.innerHTML=event.scree...
先看下这段代码:
<html>
<head>
<script language="javascript">
function xy(){
x.innerHTML=event.screenX
y.innerHTML=event.screenY
}
document.onmousemove=xy
</script>
</head>
<body>
<table cellspacing="0" cellpadding="0">
<tr bgcolor="#ffffff">
<td align="right">X:</td>
<td id="x"> </td>
</tr>
<tr bgcolor="#ffffff">
<td align="right">Y:</td>
<td id="y"> </td>
</tr>
</table>
</body>
</html>
为什么鼠标在body区域内,能获取坐标值,而出了body区域就获取不到了呢?是不是不能用document?
是用window.onmousemove=xy这个吗?可是还不行? 展开
<html>
<head>
<script language="javascript">
function xy(){
x.innerHTML=event.screenX
y.innerHTML=event.screenY
}
document.onmousemove=xy
</script>
</head>
<body>
<table cellspacing="0" cellpadding="0">
<tr bgcolor="#ffffff">
<td align="right">X:</td>
<td id="x"> </td>
</tr>
<tr bgcolor="#ffffff">
<td align="right">Y:</td>
<td id="y"> </td>
</tr>
</table>
</body>
</html>
为什么鼠标在body区域内,能获取坐标值,而出了body区域就获取不到了呢?是不是不能用document?
是用window.onmousemove=xy这个吗?可是还不行? 展开
2个回答
展开全部
<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;"> </div>
<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;"> </div>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询