Javascript 中选定的文本事件触发器

问题描述 投票:0回答:11

当有人使用鼠标在页面上选择给定文本片段时,如何触发 JavaScript 函数?
另外,有什么方法可以找到所选文本在页面上的位置吗?

更新: 更清楚地说,文本片段可以是句子、单词、短语或整个段落的一部分。

javascript jquery
11个回答
92
投票

更新: 与此同时,创建了“Text was selected”(DOM) 事件,并受到所有当前浏览器的支持:https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event

注意此事件仅适用于 form elements,即添加到

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 鼠标位置。

示例:http://www.jsfiddle.net/2C6fB/1/


71
投票

这是一个快速混搭:

$('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>

演示:http://jsfiddle.net/FvnPS/11/


15
投票

有一个新的实验性 API 可以处理这个问题:

当文档的选择对象被修改,或者与

<input>
<textarea>
关联的选择发生更改时,将触发 Selection API 的 SelectionChange 事件。在第一种情况下,selectionchange 事件在文档上触发,在第二种情况下,在元素上触发。

https://developer.mozilla.org/en-US/docs/Web/Events/selectionchange

请注意,这是前沿技术,不能保证在主流浏览器上也能正常工作。


8
投票

我不确定鼠标的事情,但这条线适用于移动设备,每次对文本选择进行更改时都会调用 -

document.addEventListener('selectionchange', () => {

});

2
投票

当您按下鼠标按钮时,会触发

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);
  }
});

1
投票

据我所知,不存在您所描述的此类事件。但您可以模拟该功能。

查看这里查看代码和演示。


1
投票

有“文本被选择”事件。但仅适用于我所知的文本区域。

<textarea onselect="message()" name="summary" cols="60" rows="5">
请写入个人简介,不少于200字!
</textarea>

0
投票

有一个快捷方式可以从事件对象中获取选定的文本。

event.currentTarget[event.currentTarget.selectedIndex].text

0
投票

您可以在 MDN 上查看。这正是您所需要的。

https://developer.mozilla.org/en-US/docs/Web/API/Element/select_event

选择完成后,触发该事件并返回所选文本。

如果您希望每次选择更改时都显示所选文本。 有针对文档和 html 输入以及文本区域的选择更改事件。 大多数浏览器都支持文档的 Selectionchange 事件,但仅 Firefox 支持 html 输入和文本区域元素。

有一个polyfill可以支持所有浏览器。

https://github.com/channyeintun/selection


0
投票

如果您想检测 JS 中选定的文本,您有 2 种方法1 种微妙之处

方法

1.通过鼠标事件

正如其他回复中提到的,您可以在

mouseup
事件上使用侦听器:

document.addEventListener("mouseup", async () => {
  setTimeout(async () => {
    console.log(window.getSelection().toString())
  }, 10)
})

2.通过键盘事件

要检测

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扩展上下文)。随着这个延迟,错误消失了。


-1
投票
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();
© www.soinside.com 2019 - 2024. All rights reserved.