gpt4 book ai didi

javascript - 将插入符号移动到 contenteditable 元素的末尾并将文本对齐到末尾

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:09:03 26 4
gpt4 key购买 nike

在我的示例中,我有 2 个问题。

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

2.在overflow中,我需要将文本下到最后,因为有免费的内容输入。

$("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/

最佳答案

尝试使用 \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();
});

和 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;
}

关于javascript - 将插入符号移动到 contenteditable 元素的末尾并将文本对齐到末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54534007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com