[英]How to use JavaScript or jQuery to wrap the selected text into a web page in a specific tag?
So I need to find a way to wrap the selected (highlighted) text in a web page into a specific tag using javascript or jQuery. 因此,我需要找到一种使用javascript或jQuery将网页中选定的(突出显示的)文本包装到特定标签中的方法。 I managed to wrap some text into the tag, but the problem is that whenever my selection includes two different paragraphs, the selected text becomes new paragraphs (ie everything becomes a mess). 我设法将一些文本包装到标签中,但是问题是,只要我的选择包括两个不同的段落,所选的文本就会变成新的段落(即,所有内容都变成一团糟)。 This is what I got (I am using the code inside a Google Chrome extension): 这就是我得到的(我正在使用Google Chrome扩展程序中的代码):
var sel = window.getSelection();
var rng = sel.getRangeAt(0);
var wrappingNode = document.createElement("myElement");
wrappingNode.appendChild(rng.extractContents());
rng.insertNode(wrappingNode);
I'm trying to find a way to prevent messing up the web page structure. 我正在尝试找到一种防止弄乱网页结构的方法。 Do you guys have any idea?? 你们有什么主意吗?
My objective is to apply a specific css style to this selected text. 我的目标是对选定的文本应用特定的CSS样式。
Thank You! 谢谢!
FF only example because of range.createContextualFragment
but something to work with. FF仅作为示例,因为range.createContextualFragment
但可以使用。 got to get to sleep! 要睡觉了!
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.highlight {color: red; }
</style>
<script>
function highlight() {
var text, sel, range;
if (window.getSelection) {
text = window.getSelection().toString();
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(range.createContextualFragment('<span class="highlight">'+text+'</span>'));
}
} else if (document.selection && document.selection.createRange) {
text = document.selection.createRange().text;
range = document.selection.createRange();
range.innerHTML = '<span class="highlight">'+text+'</span>';
}
}
</script>
</head>
<body>
<p>lorem ipsum donor kebab</p>
<button onclick="highlight()">Click me</button>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.