在IE中使事情无法选择

时间:2010-12-15 09:59:37

标签: javascript cross-browser selectable

这是我用JS编写的图表:

http://jsfiddle.net/49FVb/

css:

-moz-user-select:none;
-khtml-user-select: none;

适用于Chrome / FF,但在IE浏览器中,所有元素仍可选择,在拖动条形图时看起来很奇怪。

如何在IE中使其无法选择?

4 个答案:

答案 0 :(得分:14)

在IE中,您需要HTML中的unselectable属性:

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

...或通过JavaScript设置:

document.getElementById("foo").setAttribute("unselectable", "on");

要注意的是,不可选择的元素并不是由不可选择的元素的孩子继承的。这意味着您必须在<div>内的每个元素的开始标记中放置一个属性,或者使用JavaScript以递归方式为元素的后代执行此操作:

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

答案 1 :(得分:5)

您可以使用Javascript在所有浏览器中无法选择文字:

document.onselectstart=new Function('return false');
function noselect(e){return false;}
function click(){return true;}
document.onmousedown=noselect;
document.onclick=click;

此SO线程中描述了另一种方式:Is there a way to make text unselectable on an HTML page?

最便宜的方式可能是<body onselectstart="return false">

最好的方法是使用以下CSS:

[unselectable=on] { -moz-user-select: none; -khtml-user-select: none; user-select: none; }

并将IE unselectable property添加到您想要取消选择的元素中(HTML中为unselectable="on"; javascript中为element.setAttribute("unselectable","on")

看看这个不错的small article about unselectable text

答案 2 :(得分:1)

答案 3 :(得分:1)

到目前为止,这似乎在Chrome和IE11中运行良好,使用JQuery ...

function fMakeNodeUnselectable(node){      
    $(node).css({"cursor":"default","-moz-user-select":"-moz-none","-khtml-user-select":"none","-webkit-user-select":"none","-o-user-select":"none","user-select":"none"});
    $(node).attr("unselectable","on");
}