Chrome:所选元素不会收到“复制”事件

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

在以下示例中将焦点设置为第一个div并使用CTRL + C进行复制时,为什么第二个div会收到该事件?

const selectAreas = Array.from(document.getElementsByClassName("select-area"));
selectAreas.forEach(element => element.addEventListener('focus', (event) => {
  const windowSelection = window.getSelection();
  windowSelection.removeAllRanges();
  const range = document.createRange();
  range.selectNode(element);
  windowSelection.addRange(range);
}))

selectAreas.forEach(element => element.addEventListener('copy', (event) => {
  console.log("Copy! Area: " + element.id);
}))
<div class="select-area" id="area1" style="user-select: none" tabindex="0">
  I am text
</div>

<div class="select-area" id="area2" tabindex="0">
  I am text
</div>
javascript html google-chrome copy-paste dom-events
1个回答
0
投票

这是因为第一个元素设置为user-select: none。从文档:

元素及其子元素的文本不可选。请注意,Selection对象可以包含这些元素。

但是,此元素已明确添加到Selection中,因此它应该接收copy事件。浏览器看到此元素不可选,找到可选择的最近元素并在那里发送事件。


显然,这个人为的例子的解决方法是删除user-select: none

© www.soinside.com 2019 - 2024. All rights reserved.