Is there a way to use event.preventDefault with focusOut? If not, why?

前端 未结 4 1259
慢半拍i
慢半拍i 2021-02-07 07:18

I would like to prevent the default event from a focusOut (or blur) event and keep the focus set to the specific input field.

This is what I ha

4条回答
  •  别那么骄傲
    2021-02-07 07:28

    I'm trying to achieve this behavior in a contenteditable element. I'd like to keep the cursor where it is while clicking outside buttons that shift the focus away from the contenteditable element.

    As a solution, I intercept the focusout event and restore the original selection. Example in typescript:

    editable_element.addEventListener('focusout',(e)=> {
        if(e.relatedTarget && e.relatedTarget.tagName=="BUTTON") 
        {
            let sel : any = App.SR.getSelection();
            let range : any = sel.getRangeAt(0);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    });
    

提交回复
热议问题