Prevent text selection after double click

I'm handling the dblclick event on a span in my web app. A side-effect is that the double click selects text on the page. How can I prevent this selection from happening?


function clearSelection() {
    if(document.selection && document.selection.empty) {
        document.selection.empty();
    } else if(window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
    }
}

您还可以将这些样式应用于所有非IE浏览器和IE10的跨度:

span.no_selection {
    -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+ */
}

In plain javascript:

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

Or with jQuery:

jQuery(element).mousedown(function(e){ e.preventDefault(); });

一个简单的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";
  }
}
链接地址: http://www.djcxy.com/p/41402.html

上一篇: 如何使用jQuery禁用文本选择?

下一篇: 双击后防止文本选择