Selecting text on focus using jQuery not working in Safari and Chrome

前端 未结 9 1788
耶瑟儿~
耶瑟儿~ 2020-11-28 20:45

I have the following jQuery code (similar to this question) that works in Firefox and IE, but fails (no errors, just doesn\'t work) in Chrome and Safari. Any ideas for a wo

9条回答
  •  被撕碎了的回忆
    2020-11-28 21:27

    Just preventing default on mouseup causes the text selection to be ON at all times. The MOUSEUP event is responsible to clear the text selection. However, by preventing its default behaviour, you are unable to deselect the textusing the mouse.

    To avoid that and get the text selection to work again, you can set a flag on FOCUS, read it from MOUSEUP and reset it so future MOUSEUP events will work as expected.

    $("#souper_fancy").focus(function() {
        $(this).select();
    
        //set flag for preventing MOUSEUP event....
        $this.data("preventMouseUp", true);
    });
    
    $("#souper_fancy").mouseup(function(e) {
        var preventEvent = $this.data("preventMouseUp");
    
        //only prevent default if the flag is TRUE
        if (preventEvent) {
            e.preventDefault();
        }
    
        //reset flag so MOUSEUP event deselect the text
        $this.data("preventMouseUp", false);
    });
    

提交回复
热议问题