我正在编写一个 Firefox 插件,每当突出显示一个词时就会触发它。但是,我需要一个脚本来检测单词何时突出显示,但我被卡住了。一个例子是 nytimes.com(当你阅读一篇文章并突出显示一个词时,参考图标会弹出)。然而 nytimes.com 脚本非常复杂。我 16 岁,不是一个程序员,所以这绝对是我的联盟。
Javascript:如何检测单词是否突出显示
IT技术
javascript
events
highlight
detect
2021-01-25 07:48:06
4个回答
要做到这一点最简单的方法是检测mouseup
和keyup
对文档的事件,并检查所有文本是否被选中。以下将适用于所有主要浏览器。
示例:http : //www.jsfiddle.net/timdown/SW54T/
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
function doSomethingWithSelectedText() {
var selectedText = getSelectedText();
if (selectedText) {
alert("Got selected text " + selectedText);
}
}
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
这是一个脚本:
<script>
function getSelText()
{
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else return;
document.aform.selectedtext.value = txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()">
<form name="aform">
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>
代码蟾蜍提供:
http://www.codetoad.com/javascript_get_selected_text.asp
在您的情况下,您希望在进行选择时调用此脚本,然后您可以根据需要处理它,例如使用 AJAX 请求获取相关信息,就像 NYtimes 可能做的那样。
在我的情况下,我希望能够突出显示一行中的文本并单击该行并将我发送到其他路由,例如“/entity/:id”;
我创建了一个检测鼠标的函数正在突出显示一些文本:
export const isHighlighting = () => {
// detects mouse is highlighting a text
return window.getSelection && window.getSelection().type === 'Range';
};
然后我将其添加到
const handleClick = (id) => {
if (!isHighlighting() {
history.push(`/entity/${id}`)
}
}
{data.map((item) => (
<tr>
<td onClick={() => handleClick(item.id)}>{item.name}</>
</tr>
))}
通过这种方式,用户可以突出显示然后命名字段或单击其他位置并转到“/entity/:id”
使用rangy.js和 jQuery:
$('#elem').on('keyup mouseup', function(){
var sel = rangy.getSelection()
if (sel.rangeCount === 0 || sel.isCollapsed) return
alert(sel.toString())
})