Javascript disabling contents selection
onmousedown
and draggin
the开发者_如何学运维 contents of Container will be selected.
How can I disable this selection behaviour.
I've written Prototype.JS methods for this, you can use them.
Element.addMethods({
/**
* Makes element unselectable. Disables cursor select
* @param {Object} target
*/
setUnselectable: function(target){
if (typeof target.onselectstart != "undefined") {target.onselectstart = function(){return false;};}
else if (typeof target.style.MozUserSelect != "undefined") { target.style.MozUserSelect = "none";}
else {target.onmousedown = function(){ return false;}; }
return target;
},
/**
* Reverts unselectable effect, Enables cursor select
* @param {Object} target
*/
setSelectable: function(target){
if (typeof target.onselectstart != "undefined") { target.onselectstart = document.createElement("div").onselectstart; }
else if (typeof target.style.MozUserSelect != "undefined") { target.style.MozUserSelect = document.createElement("div").style.MozUserSelect; }
else { target.onmousedown = ""; }
return target;
}
});
To make an element unselectable
$('element_id').setUnselectable();
To revert it back
$('element_id').setSelectable();
To cover all bases, set all these properties in your css:
user-select: none -webkit-user-select: none -khtml-user-select: none -moz-user-select: none
精彩评论