以下代碼是從「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