所见即所得 - 在标签中将文本区域选定内容包围后,保持选中状态

WYSIWYG - Keep textarea selection selected after surrounding it in tags?

本文关键字:包围 状态 标签 文本 所见即所得 区域      更新时间:2023-09-26

编辑:就在我发布这篇文章时,我发现了一段很容易做到这一点的代码。 :D

这篇文章有一个非常适合我的jQuery解决方案。


我有一个脚本,当用户单击按钮时,它会在文本区域中的选定文本周围添加 BBCode 标签,单击按钮后,添加标签,我使用 textarea.focus() 重新获得对文本区域的关注,但是虽然文本由于添加标签而移动,文本选择与添加标签之前的位置相同。因此,现在选择的内容不是原始选择的文本。

这是现在的文本区域内容的代码:

$('div[id*="custom_button"]').click(function () {
    var start = textarea[0].selectionStart;
    var end = textarea[0].selectionEnd;
    var replacement = '[stuff]' + textarea.val().substring(start, end) + '[/stuff]';
    textarea.val(textarea.val().substring(0, start) + replacement + textarea.val().substring(end, textarea.val().length));
    textarea.focus()
});

我想以某种方式获取所选文本,然后在添加标签后找到它,最后重新选择它......这可能吗?我缺少一些简单的解决方案吗?

尝试在textarea.focus()之前添加此行:

textarea.selectionEnd = (replacement.length)+end;