在元素中的选定文本周围添加标签 [英] Add tags around selected text in an element

查看:77
本文介绍了在元素中的选定文本周围添加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在元素中的所选文本周围添加< span> 标记?

How can I add <span> tags around selected text within an element?

例如,如果有人突出显示John,我想在其周围添加span标签。

For example, if somebody highlights "John", I would like to add span tags around it.

HTML

<p>My name is Jimmy John, and I hate sandwiches. My name is still Jimmy John.</p>

JS

function getSelectedText() {
  t = (document.all) ? document.selection.createRange().text : document.getSelection();

  return t;
}

$('p').mouseup(function(){
    var selection = getSelectedText();
    var selection_text = selection.toString();
    console.log(selection);
    console.log(selection_text);

    // How do I add a span around the selected text?
});

http://jsfiddle.net/2w35p/

这里有一个相同的问题: jQuery选择文本并在段落中添加跨度,但它使用过时的jquery方法(例如,直播),并且接受的答案有一个错误。

There is a identical question here: jQuery select text and add span to it in an paragraph, but it uses outdated jquery methods (e.g. live), and the accepted answer has a bug.

推荐答案

我有一个解决方案。获取它的selecion和deleteContent的范围,然后在其中插入一个新的 span

I have a solution. Get the Range of the selecion and deleteContent of it, then insert a new span in it .

$('body').mouseup(function(){
    var selection = getSelectedText();
    var selection_text = selection.toString();

    // How do I add a span around the selected text?

    var span = document.createElement('SPAN');
    span.textContent = selection_text;

    var range = selection.getRangeAt(0);
    range.deleteContents();
    range.insertNode(span);
});

你可以看到此处的演示

更新

绝对地,选择将同时被删除。因此,如果需要,可以使用js代码添加选择范围。

Absolutly, the selection will be delete at the same time. So you can add the selection range with js code if you want.

这篇关于在元素中的选定文本周围添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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