简体   繁体   中英

JS ev.preventDefault() stops working after switching to another window

In the following function I try to block the scrolling by keys and it works fine, but if I switch to another window and switch back to the browser window, the ev.preventDefault() function doesn't work anymore.

  • The key_next() and key_last() functions are still triggered
  • I'm using Windows 10 and chrome
    function start(){
        window.addEventListener("keyup",(ev)=>{

            if(ev.code === "ArrowUp"){
                ev.preventDefault();
                key_last();

            }
            else if(ev.code === "ArrowDown"){
                ev.preventDefault();
                key_next();
 
            }
            else if(ev.code === "ArrowLeft"){
                ev.preventDefault();
                key_last();

            }
            else if(ev.code === "ArrowRight"){
                ev.preventDefault();
                key_next();
            }
            else if(ev.code === "Space"){
                ev.preventDefault();
            }
        });
    }

I added this into my start() function, now it works even if I switch windows.

window.addEventListener("keydown",(ev)=>{
        if(ev.code === "ArrowUp" || ev.code === "ArrowDown" || ev.code === "ArrowLeft" || ev.code === "ArrowRight" || ev.code === "Space"){
            ev.preventDefault();
        }
    });

    window.addEventListener("keypress",(ev)=>{
        if(ev.code === "ArrowUp" || ev.code === "ArrowDown" || ev.code === "ArrowLeft" || ev.code === "ArrowRight" || ev.code === "Space"){
            ev.preventDefault();
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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