0

可能重复:
在javascript中动态添加/删除样式

需要编写 javascript 函数来禁用和启用元素的选择。我写了示例代码:

<style type="text/css">
.unselectable {
  -moz-user-select: -moz-none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}
.selectable {
  -moz-user-select: text;
  -khtml-user-select: text;
  -webkit-user-select: text;
  user-select: text;
}
</style>
<script>
function makeUnselectable(node) {
  if (node.nodeType == 1) {
    node.unselectable = true;
  }
  var child = node.firstChild;
  while (child) {
    makeUnselectable(child);
    child = child.nextSibling;
  }
}
function makeSelectable(node) {
  if (node.nodeType == 1) {
    node.unselectable = false;
  }
  var child = node.firstChild;
  while (child) {
    makeSelectable(child);
    child = child.nextSibling;
  }
}
</script>

但是这段代码不正确并且不起作用。如何通过javascript动态添加和删除样式组件?所有当前元素的样式和类都应该保留!

4

2 回答 2

0

我认为这是正确的:

  <style type="text/css">
    .unselectable {
      -moz-user-select: -moz-none;
      -khtml-user-select: none;
      -webkit-user-select: none;
      user-select: none;
    }
  </style>
  <script>
  function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
  }
  function addClass(ele,cls) {
    if (!this.hasClass(ele,cls)) ele.className += " "+cls;
  }
  function removeClass(ele,cls) {
    if (hasClass(ele,cls)) {
      var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
      ele.className=ele.className.replace(reg,' ');
    }
  }
  function makeUnselectable(node) {
    if (node.nodeType == 1) {
      addClass(node, "unselectable");
    }
    var child = node.firstChild;
    while (child) {
      makeUnselectable(child);
      child = child.nextSibling;
    }
  }
  function makeSelectable(node) {
    if (node.nodeType == 1) {
      removeClass(node, "unselectable");
    }
    var child = node.firstChild;
    while (child) {
      makeSelectable(child);
      child = child.nextSibling;
    }
  }
  </script>

感谢:rockycode.com/blog/addremove-classes-raw-javascript

于 2012-11-05T01:02:56.417 回答
-1

可以使用 Jquery 看一下 css 方法:http ://api.jquery.com/css/

于 2012-11-05T00:51:29.720 回答