jQuery选择文本并在段落中添加跨度
我有一个获取所选文本的函数,通过鼠标选择文本,并将其添加到变量中。 我想在所选文本中的该变量周围添加标签 – 在该段落中。
$("p").live("mouseup",function() { selection = getSelectedText(); if(selection.length >= 3) { var $spn = $("").html(selection).addClass("selected"); $("p").wrap($spn); } }); //Grab selected text function getSelectedText(){ if(window.getSelection){ return window.getSelection().toString(); } else if(document.getSelection){ return document.getSelection(); } else if(document.selection){ return document.selection.createRange().text; } }
我可以得到文本选择变量,但不是将放在段落
的选定文本周围,我的函数将其包装在外面。
如何在段落中替换它? 谢谢。
这是出错的地方:
var $spn = $("").html(selection).addClass("selected"); $("p").wrap($spn);
这意味着你要围绕段落包装span
。
我认为你的意思是做这样的事情:
var spn = '' + selection + ''; $(this).html($(this).html().replace(selection, spn));
使用.wrapInner()
代替.wrap()
尝试修剪选择并替换html内部换行符。 这有很大帮助:
$('#tweet_contents').live("mouseup",function() { selection = getSelectedText().replace(/^\s+|\s+$/g,""); if(selection.length >= 4) { var spn = ''+selection+''+selcounter+'<\/span>'+'<\/span>'; $(this).html( $(this).html().replace(/(\r\n|\n|\r)/gm," ").replace(selection, spn ) ); } });
未经测试,但应该工作:
$("p").live("mouseup",function() { selection = getSelectedText(); if(selection.length >= 3) { var $spn = $("").html(selection).addClass("selected"); $(this).html($(this).html().replace(selection, $spn); } });
我想你需要替换段落中的文字,而不是使用换行。
$("p").live("mouseup",function() { selection = getSelectedText(); if(selection.length >= 3) { var spn = "" + selection + ""); var html = $(this).html().replace(selection,spn); $(this).html(html); } });
请注意,如果段落仅包含文本而没有标记,则这只能可靠地工作。