我处理的dblclick事件在跨度在我的web应用程序。双击的副作用是,它选择了页面上的文本。我怎样才能阻止这种选择的发生呢?
当前回答
如果你正在使用Vue JS,只需追加@mousedown。防止=""到你的元素,它将神奇地消失!
其他回答
function clearSelection() {
if(document.selection && document.selection.empty) {
document.selection.empty();
} else if(window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
你也可以将这些样式应用到所有非ie浏览器和IE10的span上:
span.no_selection {
user-select: none; /* standard syntax */
-webkit-user-select: none; /* webkit (safari, chrome) browsers */
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit (konqueror) browsers */
-ms-user-select: none; /* IE10+ */
}
对于那些正在寻找Angular 2+解决方案的人。
您可以使用表单元格的按下鼠标输出。
<td *ngFor="..."
(mousedown)="onMouseDown($event)"
(dblclick) ="onDblClick($event)">
...
</td>
和阻止如果详细> 1。
public onMouseDown(mouseEvent: MouseEvent) {
// prevent text selection for dbl clicks.
if (mouseEvent.detail > 1) mouseEvent.preventDefault();
}
public onDblClick(mouseEvent: MouseEvent) {
// todo: do what you really want to do ...
}
dblclick输出继续按预期工作。
FWIW,我将user-select: none设置为那些我不希望在双击父元素的任何地方时以某种方式被选中的子元素的父元素。它确实有效!很酷的是contentteditable ="true",文本选择等仍然适用于子元素!
就像:
<div style="user-select: none">
<p>haha</p>
<p>haha</p>
<p>haha</p>
<p>haha</p>
</div>
我知道这是一个老问题,但在2021年仍然完全有效。然而,就回答而言,我没有提到Event.stopPropagation()。
OP要求dblclick事件,但从我看到同样的问题发生在指向事件。在我的代码中,我注册了一个监听器,如下所示:
this.addEventListener("pointerdown", this._pointerDownHandler.bind(this));
监听器代码如下所示:
_pointerDownHandler(event) {
// Stuff that needs to be done whenever a click occurs on the element
}
在我的元素上快速点击多次会被浏览器解释为双击。根据元素在页面上的位置,双击将选择文本,因为这是给定的行为。
您可以通过在侦听器中调用Event.preventDefault()来禁用该默认操作,这至少在某种程度上解决了问题。
然而,如果你在一个元素上注册了一个监听器,并编写了相应的“处理”代码,你也可以吞下事件,这就是event . stoppropagation()所确保的。因此,处理程序看起来如下所示:
_pointerDownHandler(event) {
event.stopPropagation();
// Stuff that needs to be done whenever a click occurs on the element
}
因为事件已经被我的元素消耗了,层次结构更上层的元素不知道该事件,也不会执行它们的处理代码。
如果让事件冒泡,层次结构中的更高层次的元素都将执行它们的处理代码,但被event . preventdefault()告知不要这样做,这对我来说比从一开始就防止事件冒泡更没有意义。
为了防止ie8按CTRL和SHIFT点击文本选择个别元素
var obj = document.createElement("DIV");
obj.onselectstart = function(){
return false;
}
防止在文件上选择文本
window.onload = function(){
document.onselectstart = function(){
return false;
}
}