响应 HTML 文本区域中的选择更改
Reacting to selection changes in an HTML textarea
对于 HTML textarea 元素,我如何才能回调其中编辑的文本的所有选择更改?
(我目前正在使用结合 keyup、keypress 和 mousemove(用于拖动选择端点)的 hack,也许可以添加更多,但这并不完美。)
我在 HTML 文档或 Stack Overflow 上找不到它。
'all selection changes' 我的意思是包括在使用鼠标选择期间的连续变化,而且我还想在选择折叠时以及只有插入符号移动时(选择为零)得到回调长度,但变化)。我想没有别的办法,只能通过结合很多事件来实现。甚至用一个区间回调,简单的比较,也不是很好
您可以使用 onselect event:
object.addEventListener("select", myScript);
您希望 selectionchange
全球活动在 window
或 document
上可用。了解它 here。
为您的文本区域添加唯一 ID:
<textarea id="unique-id"></textarea>
向文档添加事件侦听器:
function handleSelection() {
const activeElement = document.activeElement
// Make sure this is your textarea
if (activeElement && activeElement.id === 'unique-id') {
const range = {
start: activeElement.selectionStart,
end: activeElement.selectionEnd
}
// Do something with your range
}
}
document.addEventListener('selectionchange', handleSelection)
这将 运行 handleSelection
函数中的任何代码。
对于 HTML textarea 元素,我如何才能回调其中编辑的文本的所有选择更改?
(我目前正在使用结合 keyup、keypress 和 mousemove(用于拖动选择端点)的 hack,也许可以添加更多,但这并不完美。)
我在 HTML 文档或 Stack Overflow 上找不到它。
'all selection changes' 我的意思是包括在使用鼠标选择期间的连续变化,而且我还想在选择折叠时以及只有插入符号移动时(选择为零)得到回调长度,但变化)。我想没有别的办法,只能通过结合很多事件来实现。甚至用一个区间回调,简单的比较,也不是很好
您可以使用 onselect event:
object.addEventListener("select", myScript);
您希望 selectionchange
全球活动在 window
或 document
上可用。了解它 here。
为您的文本区域添加唯一 ID:
<textarea id="unique-id"></textarea>
向文档添加事件侦听器:
function handleSelection() {
const activeElement = document.activeElement
// Make sure this is your textarea
if (activeElement && activeElement.id === 'unique-id') {
const range = {
start: activeElement.selectionStart,
end: activeElement.selectionEnd
}
// Do something with your range
}
}
document.addEventListener('selectionchange', handleSelection)
这将 运行 handleSelection
函数中的任何代码。