Jquery:如何关注DIV的最后一个字符

Jquery: How to focus on last character of DIV

本文关键字:最后一个 字符 DIV 何关注 Jquery      更新时间:2023-09-26

我有一个内容可编辑的DIV。

  1. 我想在添加文本时专注于最后一个字符。

.HTML:

<div id="messageBox" contenteditable="true" class="message"></div>

我试过了,但这段代码不正确:小提琴

  1. 如何在那里创建新行和光标焦点?

你可以在一些javascript的帮助下完成这个。下面是将光标设置为文本末尾的示例

JSFiddle Link

<div id="messageBox" contenteditable="true" class="message"></div>
<input type='button' class='btn' value='button'>

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}
$('.btn').click(function() {
    $('#messageBox').html('ok');
    placeCaretAtEnd($('#messageBox').get(0));
});