Home  >  Article  >  Web Front-end  >  Native js implementation of addclass, removeclass, toggleclasss examples

Native js implementation of addclass, removeclass, toggleclasss examples

高洛峰
高洛峰Original
2016-12-05 14:34:551384browse

jQuery操作class的方式非常强大,但是目前还有一些人不知道如何使用或者由于项目统一性的原因无法使用jquery.

在此写了一个利用原生js来实现对dom元素class的操作方法

1.addClass:为指定的dom元素添加样式
2.removeClass:删除指定dom元素的样式
3.toggleClass:如果存在(不存在),就删除(添加)一个样式
4.hasClass:判断样式是否存在

下面为一toggleClass的测试例子

<style type="text/css">
  div.testClass{
    background-color:gray;
  }
</style>
  
<script type="text/javascript">
function hasClass(obj, cls) {
  return obj.className.match(new RegExp(&#39;(\\s|^)&#39; + cls + &#39;(\\s|$)&#39;));
}
  
function addClass(obj, cls) {
  if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}
  
function removeClass(obj, cls) {
  if (hasClass(obj, cls)) {
    var reg = new RegExp(&#39;(\\s|^)&#39; + cls + &#39;(\\s|$)&#39;);
    obj.className = obj.className.replace(reg, &#39; &#39;);
  }
}
  
function toggleClass(obj,cls){
  if(hasClass(obj,cls)){
    removeClass(obj, cls);
  }else{
    addClass(obj, cls);
  }
}
  
function toggleClassTest(){
  var obj = document. getElementById(&#39;test&#39;);
  toggleClass(obj,"testClass");
}
</script>
  
<body>
  <div id = "test" style = "width:250px;height:100px;">
    sssssssssssss
  </div>
  <input type = "button" value = "toggleClassTest" onclick = "toggleClassTest();" />
</body>

   


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn