我正在尝试制作一个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'});
}
有任何想法吗?