将光标移动到输入结束

时间:2016-03-24 10:45:36

标签: javascript html

输入和setSelectionRange方法有问题。问题是我将光标位置设置在最后:

input.setSelectionRange(input.value.length,input.value.length );

光标移动到结尾但文本保持在相同位置。它适用于Firefox,但在Chrome中无效。



var input = document.querySelector("input");
input.onclick = function (){
  this.setSelectionRange(this.value.length,this.value.length )
}

<input id="beLowerCase" type="Text" value="______________________________232332" />
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:3)

我找到了简单的解决方案https://jsfiddle.net/r3yohhc0/1/,属性scrollLeft

input.scrollLeft = input.scrollWidth;

答案 1 :(得分:1)

这不是JS问题,而是CSS问题。

只需将以下CSS添加到代码中,而不是设置setSelectionRange。

<style>
input#beLowerCase {text-align:right;}
</style>

下面的工作代码:
我添加了一个而不是 ID ,因为将类型放到类中比将其写入ID更好。

&#13;
&#13;
document.querySelector("input").onclick = function() {
  var val = this.value
  this.value = "";
  this.value = val;
  this.style.textAlign = "right";
  this.style.textIndent = "-1000px";
}
document.querySelector("input").onkeydown = function() {
  this.style.textAlign = "auto";
  this.style.textIndent = "0";
}
&#13;
<input id="beLowerCase" class="align-right" type="Text" value="______________________________232332" />
&#13;
&#13;
&#13;

希望这可以解决您的问题。

<强>更新

通过JS删除样式和添加样式

更新了js小提琴链接 - https://jsfiddle.net/hsbea61b/6/

答案 2 :(得分:0)

您是否尝试动态添加CSS

text-align: right;

答案 3 :(得分:0)

使用此函数代替原生setSelectionRange:

  function setSelectionRange(input, selectionStart, selectionEnd) {
     if (input.setSelectionRange) {
        input.focus();
        var isChrome = !!window.chrome && !!window.chrome.webstore;
        if (isChrome){
             input.style.textIndent = "-1000px";
             input.onblur =function(){
                input.style.textIndent = "0px";
             };
             window.setTimeout(function() {
               input.setSelectionRange(selectionStart, selectionEnd);
             }, 0);
       }else
            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();
      }
}

事实上,在 Chrome 39 中修复了错误的兼容性问题。 所以而不是:

input.onclick = function (){
  this.setSelectionRange(this.value.length,this.value.length )
}

你将使用:

input.onclick = function (){
      setSelectionRange(this,this.value.length,this.value.length )
}

这是我测试过的fiddle

相关问题