为什么 `mouseup` PreventDefault 对所选文本的影响不同?

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

调用

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,-selecthttps://w3c.github.io/uievents/#mouseup 。鉴于没有默认操作,我的理解是调用 preventDefault()

 应该 
onlydefaultPrevented
 标记为 
true

javascript html dom
1个回答
0
投票
我想说取消选择文本发生在鼠标按下时,而选择文本发生在鼠标按下时。尝试:

Array.from(document.querySelectorAll('.broken')).forEach(el => { el.addEventListener('mouseup', ev => ev.preventDefault()) el.addEventListener('mousedown', ev => ev.preventDefault()) })
    
© www.soinside.com 2019 - 2024. All rights reserved.