[英]how to add mouseover function when mousedown is fired,and remove mouseover function when mouseup is fired javascript
window.addEventListener('mousedown' ,md ,true);
window.addEventListener('mouseup' ,mu,true);
function md(e) {
var xcoor= e.screenX;
var ycoor= e.screenY;
console.log(xcoor+'md')
window.addEventListener('mouseover' ,mo,true);
function mo(e){
var x2coor= e.screenX;
var y2coor= e.screenY;
console.log(x2coor)
}
}
function mu() {
window.removeEventListener('mousedown',md,false)
}
听起来有人不希望像机关枪一样发射一千个鼠标事件。 很高兴看到控制台如此迅速地显示所有这些坐标,但它很快就会变老。 如果您让 mouseup 事件删除 mousedown 事件处理程序,则必须编写一些过于复杂的内容来重新绑定它或重新加载页面。 有点限制。
下面的示例处理两个事件处理程序:
事件处理程序 | 事件 | 听众 | 目的 |
---|---|---|---|
init(e) |
mousedown + Ctrl键 |
window |
绑定mousemove 事件 |
evxy(e) |
mousemove |
window |
日志:鼠标事件和 XY 坐标 |
基本上,用户可以通过在按住Ctrl键(或 Mac 上的⌘ )的同时用鼠标单击页面上的任意位置来绑定和取消绑定mousemove
事件。
细节在例子中注释
// Bind the Window object to the mousedown event window.addEventListener('mousedown', init); // Define a flag let active = false; function init(e) { if (e.ctrlKey) { /* If the Ctrl key was pressed when there's a mouse click...*/ evxy(e); /* ...Run EVentXY...*/ if (!active) { /*...If the flag is false...*/ window.addEventListener('mousemove', evxy); /* ...Bind the mousemove event*/ active = true; /*...and set the flag to true */ } else { /* Otherwise...*/ window.removeEventListener('mousemove', evxy); /*Unbind the mousemove event*/ active = false; /*...and set the flag to false */ } } } function evxy(e) { let ev = e.type; let xy = [e.screenX, e.screenY]; console.log(ev + ': ' + xy); }
.as-console-row::after { width: 0; font-size: 0; } .as-console-row-code { width: 100%; word-break: break-word; } .as-console-wrapper { min-height: 100% !important; max-width: 25%; margin-left: 75%; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.