2

我们有一个 HTML 页面。是否可以(通过鼠标)选择段落中的几个单词,获取对这些选定单词的引用并以<span>...</span>编程方式通过标签封装它们?我们可以使用 jQuery 还是 HTML5/CSS3?

4

2 回答 2

3

您可以使用mouseup处理程序并使用getSelection. 假设您有一个名为 的 div testtagging,那么这是一种向该 div 中的选定文本添加跨度的方法。看到这个 jsfiddle

$('#testtagging').on('mouseup',tag);

function tag(e){
    tagSelection('<span style="color:red">$1</span>');
}

function tagSelection(html) {
    var range, node;
    if (document.selection && document.selection.createRange) {
     //IE
     range = document.selection.createRange();
     range.pasteHTML(html.replace(/\$1/,range.text));
     return true;
    }
    if (window.getSelection && window.getSelection().getRangeAt) { 
     //other browsers
     range = window.getSelection().getRangeAt(0);
     node = range.createContextualFragment(
                  html.replace(/\$1/,range.toString())
            );
     range.deleteContents();     
     range.insertNode(node);
    } 
    return true;
}​

[编辑] 也调整为与 IE 一起使用。JsFiddle 也改编了

于 2012-07-11T10:00:46.890 回答
0

JSFiddle working example

Propose to wrap all paragraph words into span elements:

var r = /(\S+)/ig;
var text = $("p").text();
$("p").html(text.replace(r, "<span class='w'>$1</span>"));

Then bind hover/click events:

$("p > .w").on("hover", function()
{
    $(this).toggleClass("hover");
})
.on("click", function()
{
    $(this).toggleClass("selected");
});

If you want to parse words from selected text range, you should use window.getSelection().

Refer to this question or ask me to adapt this code.

于 2012-07-11T09:44:20.540 回答