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