[英]Move cursor to final of input while it is highlithing the text
我需要將光標放在輸入的末尾,因為它是從開始開始的,它突出顯示了文本,因此開始了。
我嘗試使用this.selectionStart = this.selectionEnd = this.value.length;
但它不能很好地工作,或者我把它放在錯誤的行中。
謝謝 :)
window.setInterval(function() { change(); }, 1); function change() { $(function() { var elem = $('#code'); highlighter(' new ', elem, "red"); highlighter(' button', elem, "blue"); }); function highlighter(word, elem, color) { var html = elem.html(); var reg = new RegExp(word, "g"); html = html.replace(reg, "<span class='" + color + "'>" + word + "</span>"); elem.html(html); } }
.red { color: red; } .blue { color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="code" contenteditable="true"> new button </div>
var elem = $('#code'); window.setInterval(function(){ change(); }, 1); function change(){ $(function(){ highlighter(' new ', elem,"red"); highlighter(' button', elem,"blue"); }); function highlighter(word, elem, color){ var html = elem.html(); var reg = new RegExp(word,"g"); html = html.replace(reg, "<span class='"+color+"'>" + word +"</span>"); elem.html(html); } function addEvent(elem, event, fn){ if(elem.addEventListener){ elem.addEventListener(event, fn, false); }else{ elem.attachEvent("on" + event, function(){ return(fn.call(elem, window.event)); }); }} addEvent(elem,'focus',function(){ var that = this; setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0); });
下面的代碼應該實際上可以正常工作,但是由於瀏覽器問題似乎無法正常工作。
this.selectionStart = this.selectionEnd = this.value.length;
為了正確加載此文件,我增加了超時時間以消除此錯誤
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.