我处理的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中:

element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);

或者使用jQuery:

jQuery(element).mousedown(function(e){ e.preventDefault(); });
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

旧线程,但我提出了一个解决方案,我相信是更干净的,因为它不禁用每个偶数绑定到对象,只防止随机和不需要的文本选择在页面上。这很简单,而且对我来说效果很好。 这里有一个例子;我想防止当我用类“arrow-right”在对象上单击几次时的文本选择:

$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});

HTH !

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

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

防止在文件上选择文本

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