我有一个很大的段落,例如这样
<p> hello this is my paragraph </p>
所以我想在全文中给选中的文本附加一个标签 所以如果我强调“我的段落” 我希望段落如下所示
<p> hello this is <span>my paragraph</span></p>
谢谢大家
最佳答案
我正在搜索您的答案并找到:Add tags around selected text in an element .
这是我从提供的链接复制的主要代码。
<p> My sample paragraph </p>
<style>
span {color: red;}
</style>
<script type="text/javascript">
function getSelectedText() {
t = (document.all) ? document.selection.createRange().text : document.getSelection();
return t;
}
$('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);
});
</script>
关于javascript - JQuery 如何给选定的文本添加 <span> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53909535/