防止在 HTML 中进行选择

我在一个 HTML 页面上有一个 div,当我按下鼠标并移动它时,它会显示“不能丢弃”光标,就像它选择了什么一样。有没有办法禁用选择?我尝试了 CSS 用户选择,但没有成功。

76566 次浏览

The proprietary variations of user-select will work in most modern browsers:

*.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;


/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}

For IE < 10 and Opera, you will need to use the unselectable attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:

<div id="foo" unselectable="on" class="unselectable">...</div>

Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <div>. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:

function makeUnselectable(node) {
if (node.nodeType == 1) {
node.setAttribute("unselectable", "on");
}
var child = node.firstChild;
while (child) {
makeUnselectable(child);
child = child.nextSibling;
}
}


makeUnselectable(document.getElementById("foo"));

Have you got some sort of transparent image that your selecting? Usually the "cant drop" icon appears when you drag an image. Otherwise it normally selects text when you drag. If so you might have to put the image behind everything using z-index.

I use cancelBubble=true and stopPropagation() in the mouse down and move handlers.

It's seem CSS user-select don't prevent image drag and drop... so..

HTML :

<img src="ico.png" width="20" height="20" alt="" unselectable="on" /> Blabla bla blabla

CSS :

* {
user-select: none;
-khtml-user-select: none;
-o-user-select: none;
-moz-user-select: -moz-none;
-webkit-user-select: none;
}


::selection { background: transparent;color:inherit; }
::-moz-selection { background: transparent;color:inherit; }

JS :

$(function(){
$('*:[unselectable=on]').mousedown(function(event) {
event.preventDefault();
return false;
});
});

event.preventDefault() seems to do the trick (tested in IE7-9 and Chrome) :

jQuery('#slider').on('mousedown', function (e) {
var handler, doc = jQuery(document);
e.preventDefault();
doc.on('mousemove', handler = function (e) {
e.preventDefault();
// refresh your screen here
});
doc.one('mouseup', function (e) {
doc.off('mousemove', handler);
});
});