problem with Chrome form handling: input onfocus=“this.select()”

后端 未结 10 1165
猫巷女王i
猫巷女王i 2020-12-14 07:56

I\'m using the following HTML code to autoselect some text in a form field when a user clicks on the field:



        
10条回答
  •  粉色の甜心
    2020-12-14 08:09

    Building on Jason's answer, here is a function that replaces the "select" function of DOM input nodes with an updated version that has the timeout built in:

    if (/chrome/i.test(navigator.userAgent)) {
        HTMLInputElement.prototype.brokenSelectFunction = 
            HTMLInputElement.prototype.select;
    
        HTMLInputElement.prototype.select = function() {
            setTimeout(function(closureThis) { return function() {
                closureThis.brokenSelectFunction();
            }; }(this), 10);
        };
    }
    

    Basically, (in Chrome only) we just renamed the built-in but broken select() function to brokenSelectFunction() and then added a new function to all inputs called select() that calls brokenSelectFunction() after a delay. Now, just call select() normally, as the built-in select function has been replaced by the fixed function with Jason's delay suggestion.

    This way, you don't have to worry about changing your existing calls to use a wrapper function (and once this is resolved in Chrome, you can just remove the above shim and go back to normal).

    textbox.select(); // now runs select with setTimeout built-in (in Chrome only)
    

    Edit: you might want to change the user-agent match from "chrome" to "webkit", as this issue happens in all webkit-browsers including Safari, and this fix will work for any of them.

提交回复
热议问题