Looking for a better workaround to Chrome select on focus bug

前端 未结 9 1356
孤街浪徒
孤街浪徒 2020-11-30 02:56

I have the same problem as the user in this question, which is due to this bug in Webkit. However, the workaround provided will not work for my app. Let me re-state the prob

9条回答
  •  有刺的猬
    2020-11-30 03:46

    Make a bool. Set it to true after a focus event and reset it after a mouse up event. During the mouse up, if it's true, you know the user just selected the text field; therefore you know you must prevent the mouse up from happening. Otherwise, you must let it pass.

    var textFieldGotFocus = false;
    
    $('#out').focus(function()
    {
        $('#out').select();
        textFieldGotFocus = true;
    });
    
    $('#out').mouseup(function(e)
    {
        if (textFieldGotFocus)
            e.preventDefault();
    });
    
    $(document).mouseup(function() { textFieldGotFocus = false; });
    

    It's important that you put the mouseup listener that resets the variable on document, since it's not guaranteed that the user will release the mouse button over the text field.

提交回复
热议问题