我处理的dblclick事件在跨度在我的web应用程序。双击的副作用是,它选择了页面上的文本。我怎样才能阻止这种选择的发生呢?


当前回答

对于那些正在寻找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输出继续按预期工作。

其他回答

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+ */
}

或者,在mozilla上:

document.body.onselectstart = function() { return false; } // Or any html object

即,

document.body.onmousedown = function() { return false; } // valid for any html object as well

如果你正在使用Vue JS,只需追加@mousedown。防止=""到你的元素,它将神奇地消失!

对于那些正在寻找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输出继续按预期工作。

防止双击后才选择文本:

您可以使用MouseEvent#detail属性。 对于mousedown或mouseup事件,它是1加上当前的单击次数。

文档。addEventListener('mousedown',函数(事件){ If (event.detail > 1) { event.preventDefault (); //当然,你还是不知道你在这里阻止了什么… //你也可以检查event.ctrlKey/event.shiftKey/event.altKey //不阻止一些有用的东西。 } },假); 一些虚拟文本

参见https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail