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


当前回答

如果您试图完全阻止通过任何方法以及仅双击选择文本,您可以使用user-select: none css属性。我已经在Chrome 68中进行了测试,但根据https://caniuse.com/#search=user-select,它应该可以在其他当前正常的用户浏览器中工作。

从行为上看,在Chrome 68中,它是由子元素继承的,并且不允许选择元素包含的文本,即使该元素周围的文本已经被选中。

其他回答

一个简单的Javascript函数,使页面元素中的内容不可选:

function makeUnselectable(elem) {
  if (typeof(elem) == 'string')
    elem = document.getElementById(elem);
  if (elem) {
    elem.onselectstart = function() { return false; };
    elem.style.MozUserSelect = "none";
    elem.style.KhtmlUserSelect = "none";
    elem.unselectable = "on";
  }
}

我也有同样的问题。我通过切换到<a>和添加onclick="返回false;"(这样点击它就不会在浏览器历史记录中添加新的条目)。

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

为了防止ie8按CTRL和SHIFT点击文本选择个别元素

var obj = document.createElement("DIV");
obj.onselectstart = function(){
  return false;
}

防止在文件上选择文本

window.onload = function(){
  document.onselectstart = function(){
    return false;
  }
}

防止双击后才选择文本:

您可以使用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