用jQuery替换HTML后,如何将光标置于文本的末尾? [英] How to place cursor at the end of text after replacing HTML with jQuery?

查看:140
本文介绍了用jQuery替换HTML后,如何将光标置于文本的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容可编辑的div,试图用<span>标签替换<font>标签,但是在使用jQuery replaceWith()函数替换html之后,光标默认为文本的开头,但是我希望在替换结束时使用它html.

I have a contenteditable div and trying to replace <font> tag with <span> tag but after replacing the html using jQuery replaceWith() function cursor defaults to the beginning of the text however I want it at the end of the replacing html.

以下是演示,以重现此问题.让我知道重现问题是否存在.

Here is the DEMO to reproduce the issue. Let me know if there is any problem reproducing the issue.

这是演示代码要点

<div id="test" contenteditable=true>
  <p> <font color="blue">Text to be replaced</font> </p>
</div>
<a id="replace" href="javascript:void(null);">replace</a>

JS代码

$('#test').focus();
$('#replace').on({
  mousedown: function (event) {
    event.preventDefault();
  },
  click: function () {
    $('#test').find('font').replaceWith(function () {
      return '<span style="color:red">' + 'New Text' + '</span>'
    });
  }
});

在这里听起来可能是重复的问题,但是当您看到内容被替换时确实不同.我可能要替换用户选择的部分文本,而不是整个文本.因此,我需要将光标放在要替换原始html的html的末尾.

Here the problem may sound duplicate but it is indeed different as you see the content gets replaced. I might be replacing the part of that text selected by user and not the entire text. So I need to place the cursor at the end of the html which is replacing the original html.

推荐答案

您可以使用此功能

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();
    }
}

称呼它

placeCaretAtEnd( document.getElementById("content") );

示例

这篇关于用jQuery替换HTML后,如何将光标置于文本的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆