将光标移动到contenteditable元素的末尾,并将文本对齐到末尾。

4

在我的例子中,我有两个问题。

1.第一次点击时,光标没有移动到末尾。

2.在溢出时,我需要将文本对齐到末尾,因为有自由内容输入。

$("a").click(function(evt) {
  evt.preventDefault();
  var textBox = document.querySelector(".c_textBox")
  textBox.innerText += " hello  a,";
  var len = textBox.innerText.length + 1

  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(textBox.childNodes[0], len);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
  textBox.focus();
});
.c_textBox {
  display: block;
  width: 200px;
  height: 40px;
  white-space: nowrap;
  overflow: hidden;
  font-size: 1.6rem;
  border: none;
  padding-right: 3rem;
  padding-left: 2rem;
  background-repeat: no-repeat;
  background-size: 2rem;
  /* background-position: 100% 50%;*/
  background-color: lightgrey;
  border: 2px black solid;
  padding: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">add item</a><br/>
<div contenteditable="true" type='text' id="searchInput" class="c_textBox"> </div>

http://jsfiddle.net/x3pf4nu2/


var len = textBox.innerText.length + 2 将把光标移动到输入的末尾。 - oel
这可能会有所帮助 https://dev59.com/emgv5IYBdhLWcg3wMN-0#10782169 - Yinon
1个回答

2
尝试使用\u00a0作为空格。就像这样:
$("a").click(function(evt){
  evt.preventDefault();
  var textBox = document.querySelector(".c_textBox")
  textBox.innerText +="\u00a0hello\u00a0\u00a0a,";
  var len = textBox.innerText.length
  textBox.scrollLeft += textBox.innerText.length;
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(textBox.childNodes[0], len );
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
  textBox.focus();
});

And CSS:

.c_textBox{
  display:block;
  width:200px;
  height:40px;
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
  background-color:lightgrey;
  border: 2px black solid;
  padding:5px;
}

谢谢,但你知道一种将文本移动到“and”位置并且我能看到插入符的方法吗? - yantrab
如果您添加新项目,您想将光标移动到右侧并显示滚动条吗? - Mat.Now
我想要的是和输入文本时相同的行为,文本需要向左移动。 - yantrab
现在试试,希望能对你有所帮助 :) - Mat.Now
我会将overflow-x从scroll改为auto。 - atlanteh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接