如何在元素中的选定文本周围添加<span>
标记?
例如,如果有人突出显示"John",我想在它周围添加span标记。
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 select text and add span to it in an paragraph,但它使用了过时的jquery方法(例如live),并且公认的答案有一个bug。
https://stackoverflow.com/questions/24690357
复制相似问题