在以下示例中将焦点设置为第一个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>
这是因为第一个元素设置为user-select: none
。从文档:
元素及其子元素的文本不可选。请注意,Selection对象可以包含这些元素。
但是,此元素已明确添加到Selection中,因此它应该接收copy
事件。浏览器看到此元素不可选,找到可选择的最近元素并在那里发送事件。
显然,这个人为的例子的解决方法是删除user-select: none
。