【问题标题】:Move cursor to final of input while it is highlithing the text在突出显示文本时将光标移动到输入的结尾
【发布时间】:2019-02-10 20:02:25
【问题描述】:

我需要将光标放在输入的最后,因为它在开始时会突出显示文本以便开始。

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

【问题讨论】:

    标签: javascript jquery html highlight


    【解决方案1】:

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

    【讨论】:

    • 问题是我不知道放在哪里,你能把它发给我的代码吗?请:)
    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多