Google chrome, infinite loops and selecting text

前端 未结 2 500
醉酒成梦
醉酒成梦 2021-01-15 11:59

This question comes with a bit of background. Please see two other questions I\'ve recently posted that relate:

How to select text in a textbox cross-browser
I

相关标签:
2条回答
  • 2021-01-15 12:47

    Oh man, I just figured it out. This bug probably won't happen to you on a real website. It's happening because you are updating the DOM adding a "*" to the message div. When you do this, it pushes the content of the page down. This moves the top text box to where the mouse is, and the mouseup event is triggered on the top text box, causing both text boxes to fire a setTimeout and getting in an infinite loop. Total dibs on reporting this.

    edit: it's probably not the mouseup event. looks like chrome thinks you are legit focusing on both. Here's the bug test case for Chrome: http://jsfiddle.net/delvarworld/AnBE8/

    edit2: This happens in Safari too. Most likely a webkit issue.

    tldr simple workaround is to not update the dom in a way that causes reflow on the focus event, as in get rid of the html() line

    You could also try:

    $('input[type="text"]').live('mouseup', function (event) {
    

    Which works in Chrome for me

    0 讨论(0)
  • 2021-01-15 12:54

    Put any additional work in the setTimeout function. And add a clearTimeout() before you setTimeout():

    var focusTimeout = 0;
    $('input[type="text"]').live('focus', function(event) {
        var inp = this;
        clearTimeout(focusTimeout);
        focusTimeout = setTimeout(function() {
            $('#message-container').html($('#message-container').html() + "*\u200b");
            inp.select();
        }, 1);
    });
    

    http://jsfiddle.net/XppG9/19/

    In Chrome, writing the html to the page is (apparantly) causing the field to lose focus, and select() is causing it to receive focus 1ms later, thus triggering the focus event and causing the infinite loop. Moving the write html call into the function that selects the text seems to do the trick.

    0 讨论(0)
提交回复
热议问题