以下代码是从“JavaScript的通过实施例第二版”截取。我可以删除关键字var
我觉得代码
if (!e) var e = window.event; // Internet Explorer
应该
if (!e) e = window.event; // Internet Explorer
你觉得呢?这样对吗?或者,也许代码应该保持原样?
<html>
<head>
<title>Mouse Coordinates</title>
<script type="text/javascript">
function getCoords(e) {
var x = 0; // x and y positions
var y = 0;
if (!e) var e = window.event; // Internet Explorer
if (e.pageX || e.pageY) { // Firefox
x = e.pageX;
y = e.pageY;
}
else if (e.clientX || e.clientY) {
x = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
// x and y contain the mouse position
// relative to the document
alert(x + ", " + y);
}
</script>
</head>
<body>
<div style="background-color: aqua; position: absolute; top: 50px"
onmouseover="return getCoords(event);">
<h1>Mouse positions are relative to the document, not the
<div> container</h1>
</div>
</body>
</html>
使用HTML属性附加事件处理程序是*不是最佳做法 – danwellman
@danwellman:它取决于上下文。 –
@TimDown请提供一个可接受上下文的示例 – danwellman