我正在尝试使用 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;
}
谢谢!
最佳答案
您需要对选择的范围使用方法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 .
关于javascript - 使用 javascript 和 css 用鼠标选择文本的粗体部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24329827/