如何通过javascript动态添加和删除样式组件?

时间:2012-11-05 00:48:18

标签: javascript

  

可能重复:
  dynamically add/remove style in 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动态添加和删除样式组件?所有当前元素的样式和类都应该保留!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

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