Javascript禁用内容选择

时间:2010-07-27 10:51:59

标签: javascript prototypejs

mousedowndraggin上将选择Container的内容。 如何禁用此选择行为。

2 个答案:

答案 0 :(得分:1)

我为此编写了Prototype.JS方法,你可以使用它们。

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;
    }
});

使元素无法选择

$('element_id').setUnselectable();

将其还原

$('element_id').setSelectable();

答案 1 :(得分:0)

要覆盖所有基础,请在css中设置所有这些属性:

user-select: none
-webkit-user-select: none
-khtml-user-select: none
-moz-user-select: none