简体   繁体   English

在元素中的选定文本周围添加标签

[英]Add tags around selected text in an element

How can I add <span> tags around selected text within an element? 如何在元素中的选定文本周围添加<span>标记?

For example, if somebody highlights "John", I would like to add span tags around it. 例如,如果某人突出显示“John”,我想在其周围添加span标签。

HTML HTML

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

JS 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/ http://jsfiddle.net/2w35p/

There is a identical question here: jQuery select text and add span to it in an paragraph , but it uses outdated jquery methods (eg live), and the accepted answer has a bug. 这里有一个相同的问题: jQuery选择文本并在段落中添加span ,但它使用过时的jquery方法(例如live),并且接受的答案有bug。

I have a solution. 我有一个解决方案。 Get the Range of the selecion and deleteContent of it, then insert a new span in it . 获取selecion的Range并删除它的内容,然后在其中插入新的span

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

You can see the DEMO here 你可以在这里看到DEMO

UPDATE UPDATE

Absolutly, the selection will be delete at the same time. 绝对地,选择将同时被删除。 So you can add the selection range with js code if you want. 因此,如果需要,可以使用js代码添加选择范围。

You can simply do like this. 你可以这样做。

$('body').mouseup(function(){
   var span = document.createElement("span");
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
});

Fiddle 小提琴

Reference Wrapping a selected text node with span 参考用span填充选定的文本节点

You can try this: 你可以试试这个:

$('body').mouseup(function(){
   var selection = getSelectedText();
   var innerHTML = $('p').html();
   var selectionWithSpan = '<span>'+selection+'</span>';
   innerHTML = innerHTML.replace(selection,selectionWithSpan);
   $('p').html(innerHTML);    
});

and In your fiddle you are again opening a new <p> instead of a closing </p> . 在你的fiddle你又开了一个新的<p>而不是结束</p> Update that please. 请更新。

THIS WORKS ( mostly *)!! 这个工作主要是 *)!! (technically, it does what you want, but it needs HALP!) (从技术上讲,它可以做你想要的,但它需要HALP!)

JSFiddle 的jsfiddle

This adds <span ...> and </span> correctly, even if there are multiple instances of the selection in your element and you only care about the instance that's selected! 这会正确添加<span ...></span>即使元素中有多个选择实例,您只关心所选的实例!

It works perfectly the first time if you include my commented line. 如果您包含我的注释行, 它第一次完美地工作 It's after that when things get funky. 事情变得那么时髦了。

I can add the span tags, but I'm having a hard time replacing the plaintext with html. 我可以添加span标签,但是我很难用html替换明文。 Maybe you can figure it out? 也许你能搞清楚吗? We're almost there!! 我们快到了!! This uses nodes from getSelection . 这使用来自getSelection节点。 Nodes can be hard to work with though. 但节点很难使用。

document.getElementById('d').addEventListener('mouseup',function(e){
    var s = window.getSelection();
    var n = s.anchorNode; //DOM node
    var o = s.anchorOffset; //index of start selection in the node
    var f = s.focusOffset; //index of end selection in the node
    n.textContent = n.textContent.substring(0,o)+'<span style="color:red;">'
        +n.textContent.substring(o,f)+'</span>'
        +n.textContent.substring(f,n.textContent.length);
        //adds the span tag
    // document.getElementById('d').innerHTML = n.textContent;
    // this line messes stuff up because of the difference 
    // between a node's textContent and it's innerHTML.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM