捕获是否选择了文本

时间:2019-05-24 13:54:21

标签: javascript html

当您在输入框中选择文本时,下面的select document 中的这段代码会添加'You selected: ${selection}'。我可以修改它以使其在我选择任何文本时运行,而不仅仅是某些ID中的文本吗?

html

<input value="Try selecting some text in this element.">
<p id="log"></p>

javascript

function logSelection(event) {
const log = document.getElementById('log');
const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
log.textContent = `You selected: ${selection}`;
}

const input = document.querySelector('input');
input.addEventListener('select', logSelection);

在将querySelector部分添加到html之后,我尝试使用getElementById而不是<body>,但是没有用

function textSelection(event) {
  const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
  alert(selection)
}

const body = document.querySelector('body');
body.addEventListener('select', textSelection);

1 个答案:

答案 0 :(得分:0)

简短回答,不。

  

[select]事件并非适用于所有语言的所有元素。例如,在HTML中,只能在表单和元素上调度select事件。 (mdn

您可以尝试解决此问题,例如,检测何时触发了鼠标下移->移动->上移序列。

let div = document.querySelector('div');
let state = {};
div.addEventListener('mousedown', () => state.down = true);
div.addEventListener('mousemove', () => state.movedWhileDown = state.down);
div.addEventListener('mouseup', () => {
  if (state.movedWhileDown)
    console.log('maybe you selected text?');
  state = {};
});
div {
  border: 1px solid;
  width: 400px;
  height: 400px;
}
<div>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>