Chr*_*ong 11 javascript css jquery bookmarklet highlighting
我正在尝试制作一个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;
Run Code Online (Sandbox Code Playgroud)
}
但是,当我创建一个类似的函数来使用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'});
Run Code Online (Sandbox Code Playgroud)
}
有任何想法吗?
Tim*_*own 19
最简单的方法是使用execCommand(),它具有在所有现代浏览器中更改背景颜色的命令.
以下内容应该在任何选择中执行您想要的操作,包括跨越多个元素的选择.在非IE浏览器中,它会打开designMode,应用背景颜色,然后designMode再次关闭.
UPDATE
在IE 9中修复.
function makeEditableAndHighlight(colour) {
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
}
function highlight(colour) {
var range, sel;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个如何运作的粗略例子.正如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 );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13870 次 |
| 最近记录: |