以编程方式禁用CSS文本选择

时间:2013-02-20 19:58:12

标签: javascript css css3

这似乎是重复的,但继续阅读并不是这样......我想...... :)我已经按照这里的答案:How do I disable text selection with CSS or JavaScript?扭曲了。我想以编程方式禁用某些字段的选择,我在Chrome中使用:

执行此操作
node.style.webkitUserSelect="none";

哪个工作正常。但是,我尝试了以下Firefox:

node.style.mozUserSelect="none";

但这不起作用。我没有尝试过任何其他浏览器。有没有不同的方法来做到这一点?并且它是一个“文档标准”,所有CSS规则都是这样的:

.rule {
    some-css-selector: value;
}

可以像以下一样翻译成JavaScript吗?

node.style.someCssSelector="value";

或者只是运气,它在某些情况下才有效?

2 个答案:

答案 0 :(得分:4)

使用带前缀的属性时,前缀以大写字母开头,因此node.style.MozUserSelect="none";

答案 1 :(得分:2)

一个选项是创建一个CSS样式,然后以编程方式将该类添加到您想要的项目中:

<强> HTML

<div id="container">
  This is some text that should not be selectable!
</div>

<强> CSS

.noselect {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

<强> JS

var container = document.getElementById("container");
container.className += " noselect";

jsfiddle

相关问题