我一直忘了分享我的解决方案,如果不使用JS,我将找不到解决方案。在某些极端情况下,@ Jeffery A Wooden的建议CSS不会涵盖。
这就是我适用于所有UI容器的内容,无需将其应用于所有元素,因为它会在所有子元素上重复使用。
CSS:
.unselectable {
/* For Opera and <= IE9, we need to add unselectable="on" attribute onto each element */
/* Check this site for more details: http://help.dottoro.com/lhwdpnva.php */
-moz-user-select: none; /* These user-select properties are inheritable, used to prevent text selection */
-webkit-user-select: none;
-ms-user-select: none; /* From IE10 only */
user-select: none; /* Not valid CSS yet, as of July 2012 */
-webkit-user-drag: none; /* Prevents dragging of images/divs etc */
user-drag: none;
}
JS:
var makeUnselectable = function( $target ) {
$target
.addClass( 'unselectable' ) // All these attributes are inheritable
.attr( 'unselectable', 'on' ) // For IE9 - This property is not inherited, needs to be placed onto everything
.attr( 'draggable', 'false' ) // For moz and webkit, although Firefox 16 ignores this when -moz-user-select: none; is set, it's like these properties are mutually exclusive, seems to be a bug.
.on( 'dragstart', function() { return false; } ); // Needed since Firefox 16 seems to ingore the 'draggable' attribute we just applied above when '-moz-user-select: none' is applied to the CSS
$target // Apply non-inheritable properties to the child elements
.find( '*' )
.attr( 'draggable', 'false' )
.attr( 'unselectable', 'on' );
};
这比需要的要复杂得多。