gpt4 book ai didi

javascript - 通过 JavaScript 选择文本

转载 作者:行者123 更新时间:2023-11-28 00:27:26 24 4
gpt4 key购买 nike

我想选择 Html 页面上的文本并将其设为粗体,我使用以下代码

<script type="text/javascript" >


function getSelectedText(){
if(window.getSelection){ ;
return window.getSelection().toString();
}
else if(document.getSelection){;
return document.getSelection();
}
else if(document.selection){ ;

return document.selection.createRange().text;
}
}
$(document).ready(function(){
$("*").live("mouseup",
function() {
selection = getSelectedText();
alert(selection);
if(selection.length >= 3) {

$(this).html($(this).html().replace(selection, "<b>" + selection + "</b>") );

}
}
);
});

</script>

这段代码工作正常但是当文本在两个不同的段落/Div 中或者如果文本之间有链接那么它似乎不起作用。

我怎样才能让它发挥作用?

最佳答案

如果您想突出显示当前选择,使用内置的 document.execCommand() 是最简单的方法。它适用于所有主流浏览器。

以下内容应该对任何选择执行您想要的操作,包括跨越多个元素的选择。在非 IE 浏览器中,它会打开 designMode,应用背景色,然后再次关闭 designMode

更新

固定在 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 highlightSelection(colour) {
var range;
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);
}
}

document.onmouseup = function() {
highlightSelection("red");
};

实例:http://jsfiddle.net/eBqBU/9/

关于javascript - 通过 JavaScript 选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4791324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com