WYSIWYG - 在将文本区域选择包围在标签中后保持选中状态吗?
编辑:正如我发布此内容一样,我发现了一段可以轻松完成此操作的代码。 :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()
});
我正在考虑以某种方式获取所选文本,然后在添加标签后找到它,最后重新选择它......这可能吗?我缺少一些简单的解决方案吗?
Edit: Just as I posted this I found a piece of code that does it easily. :D
This post has a jQuery solution that works perfectly for me.
I have a script that adds BBCode tags around the selected text in a textarea when the user clicks on a button, After clicking the button, the tags are added, I re-gain focus on the text-area using textarea.focus()
but while the text has moved due to the added tags, the text selection is at the same position as before adding the tags. So as a result what is now selected isn't the original selected text.
Here is the code for the textarea stuff as it is now:
$('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()
});
I was thinking of somehow getting the selected text, then finding it after adding tags, and finally re-selecting it... is that at all possible? Is there some simple solution I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试在
textarea.focus()
之前添加此行:Try adding this line before
textarea.focus()
: