简体   繁体   English

如何在触发 mousedown 时添加鼠标悬停功能,并在触发 mouseup 时删除鼠标悬停功能 javascript

[英]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)
}

It sounds like someone doesn't want a thousand mouse events firing off like a machine gun.听起来有人不希望像机关枪一样发射一千个鼠标事件。 It's neat to see the console display all of those coords so rapidly but it gets old fast.很高兴看到控制台如此迅速地显示所有这些坐标,但它很快就会变老。 If you have the mouseup event remove the mousedown event handler, you'd have to write something overly complex to rebind it or reload the page.如果您让 mouseup 事件删除 mousedown 事件处理程序,则必须编写一些过于复杂的内容来重新绑定它或重新加载页面。 Kinda limiting.有点限制。

The example below deals with two event handlers:下面的示例处理两个事件处理程序:

Event Handler事件处理程序 Event事件 Listener听众 Purpose目的
init(e) mousedown + Ctrl key mousedown + Ctrl window Bind and unbind the mousemove event绑定mousemove事件
evxy(e) mousemove window Log: Mouse Events and XY coordinates日志:鼠标事件和 XY 坐标

Basically the user can bind and unbind the mousemove event by clicking anywhere on the page with the mouse while holding down the Ctrl key (or for Mac).基本上,用户可以通过在按住Ctrl键(或 Mac 上的 )的同时用鼠标单击页面上的任意位置来绑定和取消绑定mousemove事件。

Details are commented in example细节在例子中注释

 // 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM