mys*_*eie 3 javascript addeventlistener
我试图捕获每次鼠标单击画布时的screenX和值,因此我使用了,但我有点困惑的是:screenYaddEventListener
canvas = document.getElementById('theCanvas');
ctx = canvas.getContext('2d');
window.addEventListener("click",function(event){
console.log(event)
});
Run Code Online (Sandbox Code Playgroud)
在我找到 clientX 和 clientY 值后,该值指示我的鼠标在控制台屏幕上的 x/y 位置。当我尝试用任何其他单词或变量替换事件参数时,我有点困惑,它仍然在控制台中执行相同的输出,就像:
window.addEventListener("click",function(b){
console.log(b)
});
Run Code Online (Sandbox Code Playgroud)
我很好奇的是,无论我在这里向 function() 传递什么参数,它总是返回窗口对象上的所有内容吗?我已阅读https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener上的文章,但它没有涵盖这一点。那么我的好奇心可以得到帮助吗?
浏览器触发事件就是这样,它们是由浏览器触发的。因此,你不能将自己的论点传递给他们。当触发典型的浏览器事件并且已注册该事件的处理程序时,用户代理会自动调用已注册的处理程序,并且该处理程序会自动传递一个参数,该参数引用触发该处理程序的事件。从该事件中,您可以通过访问该参数来访问它具有的任何属性。参数名称仅用于函数内的代码访问传递给函数的数据。它收到的名称不会改变传递到函数中的数据。
click在您的例子中,您正在为该对象设置一个事件处理程序window,因此对事件的引用click将被传递到您的回调函数中。你无法改变这一点,你可以随心所欲地称呼这个论点。该event对象的属性将取决于生成的事件对象的类型(即,对于鼠标相关事件,您将具有 和 等属性clientX,clientY但对于键盘相关事件,您将具有 和 等属性keyCode)shiftKey。只需记录事件本身或调试事件处理函数,您就可以检查所有可用的属性,但同样,这些属性将根据您正在处理的事件类型而有所不同。
window.addEventListener("click",function(aNameThatIhaveChosen){
console.log("You have clicked at: " + aNameThatIhaveChosen.clientX + ", " + aNameThatIhaveChosen.clientY );
});Run Code Online (Sandbox Code Playgroud)
<h1>Click anywhere</h1>Run Code Online (Sandbox Code Playgroud)
现在,在某些情况下,您可能还需要将其他参数传递给事件处理函数。这可以通过将处理函数包装在另一个函数内来完成。然后,您可以将自动事件参数传递给实际处理程序,但也可以传递您自己的数据:
window.addEventListener("click", function(evt){
// We're just going to pass along the event argument to our custom function
// and add additional arguments as necessary
handleClick(evt, "My Custom Data", new Date());
});
// This is the function that will actually handle the click event.
// It will be passed the auto-generated event argument, but also
// it will be passed any custom arguments we want.
// Note that while the function above recieved the event as "evt"
// and passed that object reference to this function as "evt", this
// function is recieving it as "event". What we call the input parameters
// doesn't change what those parameters really are, only how we access them.
function handleClick(event, customA, customB){
console.log("You have clicked at: " + event.clientX + ", " + event.clientY );
console.log("The custom data was: " + customA + ", " + customB.toLocaleTimeString());
}Run Code Online (Sandbox Code Playgroud)
<h1>Click anywhere</h1>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14549 次 |
| 最近记录: |