猿问

使用Java脚本更改所选文本的CSS

我正在尝试制作一个将用作荧光笔的javascript小书签,当按小书签时,将网页上所选文本的背景更改为黄色。


我正在使用以下代码来获取选定的文本,并且工作正常,返回正确的字符串


function getSelText() {

var SelText = '';

if (window.getSelection) {

    SelText = window.getSelection();

} else if (document.getSelection) {

    SelText = document.getSelection();

} else if (document.selection) {

    SelText = document.selection.createRange().text;

}

return SelText;

}


但是,当我创建了一个类似的函数来使用jQuery更改所选文本的CSS时,它不起作用:


function highlightSelText() {

var SelText;

if (window.getSelection) {

    SelText = window.getSelection();

} else if (document.getSelection) {

    SelText = document.getSelection();

} else if (document.selection) {

    SelText = document.selection.createRange().text;

}

$(SelText).css({'background-color' : 'yellow', 'font-weight' : 'bolder'});

}


有任何想法吗?


慕容森
浏览 623回答 3
3回答

四季花海

最简单的方法是使用execCommand(),该命令具有在所有现代浏览器中更改背景颜色的命令。以下应该在任何选择上做您想要的,包括跨越多个元素的选择。在非IE浏览器中,它会打开designMode,应用背景色,然后designMode再次关闭。更新在IE 9中修复。function makeEditableAndHighlight(colour) {&nbsp; &nbsp; var range, sel = window.getSelection();&nbsp; &nbsp; if (sel.rangeCount && sel.getRangeAt) {&nbsp; &nbsp; &nbsp; &nbsp; range = sel.getRangeAt(0);&nbsp; &nbsp; }&nbsp; &nbsp; document.designMode = "on";&nbsp; &nbsp; if (range) {&nbsp; &nbsp; &nbsp; &nbsp; sel.removeAllRanges();&nbsp; &nbsp; &nbsp; &nbsp; sel.addRange(range);&nbsp; &nbsp; }&nbsp; &nbsp; // Use HiliteColor since some browsers apply BackColor to the whole block&nbsp; &nbsp; if (!document.execCommand("HiliteColor", false, colour)) {&nbsp; &nbsp; &nbsp; &nbsp; document.execCommand("BackColor", false, colour);&nbsp; &nbsp; }&nbsp; &nbsp; document.designMode = "off";}function highlight(colour) {&nbsp; &nbsp; var range, sel;&nbsp; &nbsp; if (window.getSelection) {&nbsp; &nbsp; &nbsp; &nbsp; // IE9 and non-IE&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!document.execCommand("BackColor", false, colour)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; makeEditableAndHighlight(colour);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } catch (ex) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; makeEditableAndHighlight(colour)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else if (document.selection && document.selection.createRange) {&nbsp; &nbsp; &nbsp; &nbsp; // IE <= 8 case&nbsp; &nbsp; &nbsp; &nbsp; range = document.selection.createRange();&nbsp; &nbsp; &nbsp; &nbsp; range.execCommand("BackColor", false, colour);&nbsp; &nbsp; }}

侃侃无极

这是它如何工作的粗略示例。正如Zack指出的那样,您需要注意选择跨越多个元素的情况。这并不是按原样使用的,只是可以帮助使想法流传的东西。在Chrome中测试。var selection = window.getSelection();var text = selection.toString();var parent = $(selection.focusNode.parentElement);var oldHtml = parent.html();var newHtml = oldHtml.replace(text, "<span class='highlight'>"+text+"</span>");parent.html( newHtml );
随时随地看视频慕课网APP
我要回答