我处理的dblclick事件在跨度在我的web应用程序。双击的副作用是,它选择了页面上的文本。我怎样才能阻止这种选择的发生呢?
当前回答
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+ */
}
其他回答
一个简单的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";
}
}
或者,在mozilla上:
document.body.onselectstart = function() { return false; } // Or any html object
即,
document.body.onmousedown = function() { return false; } // valid for any html object as well
FWIW,我将user-select: none设置为那些我不希望在双击父元素的任何地方时以某种方式被选中的子元素的父元素。它确实有效!很酷的是contentteditable ="true",文本选择等仍然适用于子元素!
就像:
<div style="user-select: none">
<p>haha</p>
<p>haha</p>
<p>haha</p>
<p>haha</p>
</div>
对于那些正在寻找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
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔