将光标整理在文本上方时,将光标移至输入的结尾

时间:2018-09-05 15:49:44

标签: javascript jquery html highlight

我需要将光标放在输入的末尾,因为它是从开始开始的,它突出显示了文本,所以就开始了。

我尝试使用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>

1 个答案:

答案 0 :(得分:0)

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);

相关问题