Replacement for deprecated `keypress` DOM event

前端 未结 2 848
长情又很酷
长情又很酷 2020-12-07 01:08

According to MDN article keypress event is deprecated:

But I can\'t find any information elsewhere on whether we should use this event in a new

2条回答
  •  借酒劲吻你
    2020-12-07 02:01

    Not super hard to work around unless (shame on you) you or something you use has been clobbering event bubbling indiscriminately at every opportunity.

    Simple but powerful utility like this is exactly why you should only do that for isolated node leaves of your HTML.

    In those cases where you did have to prevent keydown bubbling you could simply wrap the following in a function that takes an argument in place of document.body and simply apply at the point where bubbling is stopped if you still want 'keypress2' events available to that HMTL.

    const keyBlacklist = [
        'Shift',
        'Alt',
        'Control',
        'Meta'
    ];
    
    document.body.addEventListener('keydown',(e)=>{
        if(keyBlacklist.indexOf(e.key) === -1){
            const newKeyPress = new CustomEvent('keypress2',{detail:e});
            e.target.dispatchEvent(newKeyPress);
        }
    });
    
    document.body.addEventListener('keypress2',e=>{console.log(e.detail);});
    

提交回复
热议问题