调用
mouseupEvent.preventDefault()
通常不会阻止创建新选择,除非您尝试在当前选择中创建选择。
Array.from(document.querySelectorAll('.broken')).forEach(el => el.addEventListener('mouseup', ev => ev.preventDefault()))
<div class="broken">
Try selecting THIS TEXT, next try to click within the selection to deselect (select a collapsed selection.
</div>
<div class="broken" contenteditable>
This is a contenteditable div, which makes the difference even far clearer, as it visualizes a collapes selection.
</div>
<div>
And this is a normal div for reference without an event listener, when you select text in this div you can unselect it by clicking within the selection.
</div>
选定文本和未选定文本之间的行为差异的原因是什么?我希望对
either
的
preventDefault
调用始终阻止创建新选择,或者永远不会阻止创建新选择。
无论它的价值如何,这种行为在 Chrome 和 Firefox 之间是一致的,但规范规定不应该有 mouseup 的默认操作:
https://w3c.github.io/uievents/#event-flow-default-cancel:~:text=Yes-,None,-select 和 https://w3c.github.io/uievents/#mouseup 。鉴于没有默认操作,我的理解是调用 preventDefault()
应该only 将
defaultPrevented
标记为
true
。
Array.from(document.querySelectorAll('.broken')).forEach(el => {
el.addEventListener('mouseup', ev => ev.preventDefault())
el.addEventListener('mousedown', ev => ev.preventDefault())
})