当有人使用鼠标在页面上选择给定文本片段时,如何触发 JavaScript 函数?
另外,有什么方法可以找到所选文本在页面上的位置吗?
更新: 更清楚地说,文本片段可以是句子、单词、短语或整个段落的一部分。
更新: 与此同时,创建了“Text was selected”(DOM) 事件,并受到所有当前浏览器的支持:https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event
HTMLInputElement
API
没有“Text was selected”
(DOM)
事件,但您可以将mouseup
事件绑定到document.body
。在该事件处理程序中,您可能只需检查
document.selection.createRange().text
或
window.getSelection()
方法。 Stackoverflow 上有几个主题,比如这个 javascript to get paragraph of selected text in web page.
我不确定“查找位置”是什么意思,但为了留在我的示例世界中,您可以使用
event propertys
来表示 X+Y 鼠标位置。
这是一个快速混搭:
$('div').mouseup(function() {
var text=getSelectedText();
if (text!='') alert(text);
});
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
<div>Here is some text</div>
有一个新的实验性 API 可以处理这个问题:
当文档的选择对象被修改,或者与
<input>
或 <textarea>
关联的选择发生更改时,将触发 Selection API 的 SelectionChange 事件。在第一种情况下,selectionchange 事件在文档上触发,在第二种情况下,在元素上触发。
https://developer.mozilla.org/en-US/docs/Web/Events/selectionchange
请注意,这是前沿技术,不能保证在主流浏览器上也能正常工作。
我不确定鼠标的事情,但这条线适用于移动设备,每次对文本选择进行更改时都会调用 -
document.addEventListener('selectionchange', () => {
});
当您按下鼠标按钮时,会触发
mousedown
事件,当释放鼠标按钮时,会触发 mouseup
和 click
事件。
因此我们监听
mouseup
事件并检查是否已选择任何文本,并执行相应的操作。
const p = document.getElementById('interactiveText');
p.addEventListener('mouseup', (e) => {
const selection = window.getSelection().toString();
if (selection === '') {
console.log('click');
} else {
console.log('selection', selection);
}
});
据我所知,不存在您所描述的此类事件。但您可以模拟该功能。
查看这里查看代码和演示。
有“文本被选择”事件。但仅适用于我所知的文本区域。
<textarea onselect="message()" name="summary" cols="60" rows="5">
请写入个人简介,不少于200字!
</textarea>
有一个快捷方式可以从事件对象中获取选定的文本。
event.currentTarget[event.currentTarget.selectedIndex].text
您可以在 MDN 上查看。这正是您所需要的。
https://developer.mozilla.org/en-US/docs/Web/API/Element/select_event
选择完成后,触发该事件并返回所选文本。
如果您希望每次选择更改时都显示所选文本。 有针对文档和 html 输入以及文本区域的选择更改事件。 大多数浏览器都支持文档的 Selectionchange 事件,但仅 Firefox 支持 html 输入和文本区域元素。
有一个polyfill可以支持所有浏览器。
如果您想检测 JS 中选定的文本,您有 2 种方法 和 1 种微妙之处。
正如其他回复中提到的,您可以在
mouseup
事件上使用侦听器:
document.addEventListener("mouseup", async () => {
setTimeout(async () => {
console.log(window.getSelection().toString())
}, 10)
})
要检测
select all
键盘快捷键:
document.addEventListener("keydown", async (event) => {
if ((event.metaKey || event.ctrlKey) && event.key === "a") {
setTimeout(async () => {
console.log(window.getSelection().toString())
}, 10)
}
})
在这里,您需要检测
Ctrl + A
(Windows)或Cmd + A
(Mac)。
为什么在我的示例中使用
setTimeout
?使用短暂的延迟来让浏览器完成选择操作。这是为了避免干扰默认行为。有时我有时会遇到检测问题(Chrome扩展上下文)。随着这个延迟,错误消失了。
var selectedText = "";
if (window.getSelection) {
selectedText = window.getSelection();
}
if (document.getSelection) {
selectedText = document.getSelection();
}
if (document.selection) {
selectedText = document.selection.createRange().text;
}
function textSelector() {
alert(selectedText);
}
textSelector();