chrome setSelectionRange() not work in oninput handler

送分小仙女□ 提交于 2019-12-03 13:03:15

There are some problems with your code, namely that the parameters passed into the select() function are wrong: this will be window and e will be undefined. Also, using select() as a function name within the oninput attributes causes a problem because select will resolve to the select() method of the input itself. A better approach is usually to set the event handler in script rather than via an event handler attribute.

However, the problem exists even after correcting these issues. Possibly the input event fires before the browser has moved the caret in Chrome. A simple workaround would be to use a timer, although this is sub-optimal because there's a possibility the user will be able to input another character before the timer fires.

Demo: http://jsfiddle.net/XXx5r/2/

Code:

<input type="text" oninput="selectText(this)">

<script type="text/javascript">
function selectText(input) {
    var s = input.value;
    if (s.length) {
        window.setTimeout(function() {
            input.setSelectionRange(s.length-1, s.length);
        }, 0);
    }
}
</script>

    
    
    var $input = document.getElementById('my_id');
    
    $input.onfocus = function () {
       $input.setSelectionRange(0, 7);
    }
    $input.focus();
    
    
<input type='text' id='my_id' value="My text for example." />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!