Sky*_*ell 3 html javascript css jquery
我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
您需要在选择范围上使用surroundContents方法.不幸的是,每个浏览器都不支持该功能,因此您需要注意这一点.
var range = selection.getRangeAt(0);
if(selection.toString().length > 2){
var newNode = document.createElement("span");
newNode.setAttribute("class", "selectedText");
range.surroundContents(newNode);
}
Run Code Online (Sandbox Code Playgroud)
在这里工作演示.
请参阅此处的文档.