在js中,光標是一個對象,當你選中某個元素的時候才會出現光標對象。比如:我們點擊一個輸入框,實際會產生一個選中對象-selection,這個對象我們可以通過indow.getSelection()來獲取;selection只存在1個,所以當你切換到其他輸入框額時候,selection同樣會跟着變化的。在選中的情況下有一個光標叫做range,和selection一樣。
在contenteditable 屬性中,當點擊該區域的時候,光標默認顯示在區域內容最后一位。如:
<div id="box" contenteditable=true> 這是內容哦! </div>
需要點擊才出現光標,而且它的位置在內容區域的最后面,如果我們需要打開頁面默認就出現,而且出現在第一個位置上,該如何實現呢?下面將給出js的實現方法:
熊貓辦公https://www.wode007.com/sites/73654.html
方法一:
1 var p = document.getElementById('box'), 2 s = window.getSelection(), 3 r = document.createRange(); 4 r.setStart(p, 0); 5 r.setEnd(p, 0); 6 s.removeAllRanges(); 7 s.addRange(r);
如果你需要把元素清空,或者對應內容為空的時候,你可以這樣做:
1 var p = document.getElementById('box'), 2 s = window.getSelection(), 3 r = document.createRange(); 4 p.innerHTML = '\u00a0'; 5 r.selectNodeContents(p); 6 s.removeAllRanges(); 7 s.addRange(r); 8 document.execCommand('delete', false, null);
方法二:
1 var box= document.getElementById('box'); 2 setTimeout(function() { 3 box.focus(); 4 }, 0);
給box設置獲取焦點。然后放置setTimeout中,延遲執行。