-2

只是想用我目前非常有限的 JavaScript 知识来找点乐子。

http://jsfiddle.net/pDMq9/

为什么这不起作用?我做错了什么?

HTML

<body>

<input type="button" value="Click me" id="button" />

</body>

Javascript

var x = e.clientX;
var y = e.clientY;

var p = document.getElementById("button");

function mousedown() {
    if (p.mousedown) {
        alert(x, y);
    }
}
4

6 回答 6

8
  1. 您尝试从mousedown函数外部的事件中获取值(即在事件存在之前)
  2. 您永远不会将mousedown函数分配为事件处理程序
  3. 您不接受 mousedown函数的任何参数
  4. 您无缘无故地测试函数内部的mousedown 属性mousedown
  5. 您将多个参数传递给alert

所以要修复它:

function mousedownHandler(e) {
    var x = e.clientX;
    var y = e.clientY;
    alert(x + ", " + y);
}

var p = document.getElementById("button");
p.addEventListener('mousedown', mousedownHandler);
于 2013-11-04T16:24:59.267 回答
1

您必须将clickormousedown事件附加到元素。在函数内部,您可以获取事件并clientX从中检索clientY

JavaScript

var p = document.getElementById("button");

p.onclick = function mousedown(e) {
    var x = e.clientX;
    var y = e.clientY;
    alert(x + ' ' + y);
}

演示

http://jsfiddle.net/8gzMj/

于 2013-11-04T16:25:51.797 回答
0
  1. e不是全局变量。通常e是与事件处理程序关联的事件:

           function mousedownHandler(e)
           {
               //manage the event
               console.log(e.clientX, e.clientY);
           }
    
  2. 事件处理程序应绑定到相应的事件:

      var p = document.getElementById("button");
      p.onmousedown = mousedownHandler;
    

是您在 jsFiddle 中的示例的运行分支。

于 2013-11-04T16:29:28.283 回答
0

首先,您需要将事件附加到元素。然后你需要传入'e'或事件。然后你可以阅读它的属性。

var p = document.getElementById("button");

p.addEventListener('mousedown', mousedown);

function mousedown(e) {
    var x = e.clientX;
    var y = e.clientY;

    alert(x, y);

}

http://jsfiddle.net/cSUfL/

于 2013-11-04T16:29:38.460 回答
-1

你不调用函数,你必须使用这个

  <body>

 <input type="button" value="Click me" id="button" onClick="mousedown()" />

 </body>
于 2013-11-04T16:28:16.830 回答
-1
<!DOCTYPE html>
<html>
<head>
    <title>HTML</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        function mousedown(e) {
            var x = e.clientX;
            var y = e.clientY;
            alert(x + "\n" + y);
        }
    </script>
</head>
<body>
    <table>
        <input type="button" value="Click me" id="button" onmousedown="mousedown(event);" />
        <!-- alternatively -->
        <button id="button2" onmousedown="mousedown(event)">Click me</button>
    </table>
</body>
</html>
于 2013-11-04T16:42:35.953 回答