以下代码摘自“JavaScript by Example Second Edition”。
我想的代码
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>
最佳答案
代码就目前而言是正确的,但没有 var
关键字也可以工作。
由于 e
是函数的形式参数(无论是否传递),因此无需将其声明为 var
。
在 MSIE 上 e
没有被传递,所以它被赋予了全局 window.event
对象的值。
请注意,var
关键字本身不会覆盖任何现有值,它仅用于声明局部范围内的变量.如果变量已经有一个值,则“提升”会将声明移动到范围的顶部,但将任何赋值保留在原处。
一个更惯用的写法是:
function getCoords(e) {
e = e || window.event;
...
}
关于javascript - 我可以删除 var 关键字吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12578049/