我正在尝试使用javascript& css创建一个小工具,允许用户用鼠标选择文本区域(整个单词,单词的一部分,单个字符),然后单击一个按钮,然后加粗选择。
我有2件工作:我可以加粗整个区域,我可以将鼠标选择写入控制台。
但我无法弄清楚如何只粗体化用鼠标选择的文本部分。
我这里有一个jsfiddle: http://jsfiddle.net/75EwZ/4/
以下是代码:
$(".boldtrigger").click(function() {
var selection = getSelText();
console.log('selected value', selection);
//only bold text that is selected
//get contents of .text
//replace selected section with <span class="selectedText"></span>
//ex: user selects the word "the" with the mouse:
//<div class="text">Testing the waters</div> becomes:
//<div class="text">Testing <span class="selectedText">the</span> waters</div>
//then bold contents of .selectedText
$(".text").toggleClass("bold");
});
function getSelText()
{
var txt = '';
if (window.getSelection)
{ txt = window.getSelection(); }
else if (document.getSelection)
{ txt = document.getSelection(); }
else if (document.selection)
{ txt = document.selection.createRange().text; }
else return;
return txt;
}
谢谢!
答案 0 :(得分:5)
您需要在选择的范围上使用 surroundContents 方法。不幸的是,每个浏览器都不支持该功能,因此您需要注意这一点。
var range = selection.getRangeAt(0);
if(selection.toString().length > 2){
var newNode = document.createElement("span");
newNode.setAttribute("class", "selectedText");
range.surroundContents(newNode);
}
工作演示here。
请参阅文档here。
答案 1 :(得分:1)
您应该看到document.execCommand方法: https://developer.mozilla.org/fr/docs/Rich-Text_Editing_in_Mozilla
答案 2 :(得分:-1)
完成本教程Get Selected text through jquery。使用相同的代码获取所选部分,然后点击按钮将其替换为<b>"selected text"</b>
。