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

前端 未结 9 1790
耶瑟儿~
耶瑟儿~ 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:31

    Because there is flickering when you use setTimeout, there is another event based solution. This way the 'focus' event attach the 'mouseup' event and the event handler detach itself again.

        function selectAllOnFocus(e) {
        if (e.type == "mouseup") { // Prevent default and detach the handler
            console.debug("Mouse is up. Preventing default.");
            e.preventDefault();
            $(e.target).off('mouseup', selectAllOnFocus);
            return;
        }
        $(e.target).select();
        console.debug("Selecting all text");
        $(e.target).on('mouseup', selectAllOnFocus);
    }
    

    Then wire the first event

        $('.varquantity').on('focus', selectAllOnFocus);
    

提交回复
热议问题