javascript 设置插入符号位置总是以 contenteditable div 结尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16230720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:49:29  来源:igfitidea点击:

Set the caret position always to end in contenteditable div

javascriptjqueryhtmlpositioncaret

提问by Mr_Green

In my project, I am trying to set the caret position always to the end of the text. I know this is default behaviour but when we add some text dynamically, then the caret position changes to starting point in Chrome and firefox (IE is fine, amazing).

在我的项目中,我试图将插入符号位置始终设置在文本的末尾。我知道这是默认行为,但是当我们动态添加一些文本时,插入符号位置会更改为 Chrome 和 firefox 中的起点(IE 很好,很棒)。

Anyway to make it to work properly in chrome and firefox?

无论如何让它在chrome和firefox中正常工作?

Here is the fiddle

这是小提琴

<div id="result" contenteditable="true"></div>
<button class="click">click to add text</butto>


var result = $('#result');
$('.click').click(function () {
    var preHtml = result.html();
    result.html(preHtml + "hello");
    result.focus();
});

I tried adding setStartand setEndas mentioned in this linkbut no use.

我尝试添加setStartsetEnd在此链接中提到但没有用。

回答by Mr_Green

I got the solution herethanks to Tim down :). The problem was that I was calling

感谢蒂姆,我在这里得到了解决方案:)。问题是我在打电话

placeCaretAtEnd($('#result'));

Instead of

代替

placeCaretAtEnd(($('#result').get(0));

as mentioned by jwarzech in the comments.

正如 jwarzech 在评论中提到的。

Working Fiddle

工作小提琴