顯示輸入框時光標自動定位到輸入框內容的最后


思路就是利用input元素中的setSelectionRange方法

setSelectionRange(posstart,posend)用來選中被focus的輸入框的特定范圍.

開始位置和結束位置設置為內容的總長度,光標就會定位到內容最右邊。

    <body>
        <input id="textarea-1" onfocus="setCss(this)" type="text" name="" value="這是一個自動讓光標定位到文本框的最后面的一個demo" autofocus >
        <button class="btn" onclick="setCss()">定位光標</button>
    </body>
    <script>

    function setCss(opt){
            var sr=document.getElementById("textarea-1");
            var len = sr.value.length;
            setSelectionRange(sr,len,len); //將光標定位到文本最后 
        }

        function setSelectionRange(input, selectionStart, selectionEnd) {
            if (input.setSelectionRange) {  
                input.focus();  
                input.setSelectionRange(selectionStart, selectionEnd);  
            }  
            else if (input.createTextRange) {  
                var range = input.createTextRange();  
                range.collapse(true);  
                range.moveEnd('character', selectionEnd);  
                range.moveStart('character', selectionStart);  
                range.select();  
            } 
        } 
      
    </script>

需要注意到是,元素一定要被選中然后才能通過setSelectionRange方法設置選中。

這里有個這樣的需求,在點擊按鈕時光標定位到輸入框最后面同時輸入框到內容顯示到最后面。

先給輸入框設置autofocus自動定位,然后自動調用onfocus方法先調用一次setCss,讓輸入框聚焦,然后再點擊按鈕再調用setCss一次,這時輸入框已經聚焦了,setSelectionRange調用有效。

在crome上測試,第一次調用setSelectionRange,光標移到了輸入框內容最后面,但是內容顯示沒有定位到最后面,需要調用第二次才可以。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM