Unable to focus an input using JavaScript in IE11

前端 未结 3 1332
孤独总比滥情好
孤独总比滥情好 2021-01-12 14:41

I\'m unable to get IE11 to focus an input element after it is inserted into the DOM. The element won\'t receive text input after being focused, but its placeholder text is n

相关标签:
3条回答
  • 2021-01-12 15:10

    I don't think that your issue is coming from the focus() function, I think it's coming from the selector.

    To prove it I just opened my IE11 and tried to focus the SO search input on the top right of the page using the following command:

    document.getElementById('search')[0].focus()
    

    So, just open your IE console (F12) and type that, it should focus the search input. If so, then the issue is coming from the selector which isn't an input as you may think.

    It works on my IE 11.0.9600.17905

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

    The issue was focusing in IE11 is broken when the css property -ms-user-select: none is applied to the input. So by changing:

    * {
      -ms-user-select: none;
    }
    

    into

    *:not(input) {
      -ms-user-select: none;
    }
    

    I was able to solve the problem. Here is a codepen for reproducing the issue: http://codepen.io/anon/pen/yNrJZz

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

    As stated in https://stackoverflow.com/a/31971940, running element.focus() has no effect in IE11 when the css property -ms-user-select: none is set. A workaround can be

    element.style['-ms-user-select'] = 'text';
    element.focus()
    element.style['-ms-user-select'] = '';
    

    Does not work in IE: https://codepen.io/macjohnny-zh/details/WPXWvy
    (Code: https://codepen.io/macjohnny-zh/pen/WPXWvy)

    Works in IE, too: https://codepen.io/macjohnny-zh/details/LqOvbZ
    (Code: https://codepen.io/macjohnny-zh/pen/LqOvbZ)

    Note: this also happens e.g. for

    :-ms-input-placeholder {
      -ms-user-select: none;
    }
    

    See https://github.com/angular/material2/issues/15093

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