Home > Web Front-end > JS Tutorial > body text

How to call class in JavaScript

亚连
Release: 2018-06-23 18:11:37
Original
3110 people have browsed it

下面小编就为大家带来一片JavaScript中关于class的调用方法。具有很好的参考价值,希望对大家有所帮助

PS:class的调用,其实是可以叠加的,当然了这要求样式不同的情况下,如果样式相同,则后一个样式会覆盖前一个样式。

1、举例如下:

<p id="test" class="aaa bbb">测试关于class的调用</p>
Copy after login
.aaa{
 font-size:20px;
 color:red; 
}
.bbb{
 font-size:50px;
 color:green;
}
Copy after login
var test=document.getElementById(&#39;test&#39;);
test.className=&#39;aaa&#39;;
test.className=&#39;aaa bbb&#39;;//因为aaa和bbb的样式相同,所以,bbb的样式会覆盖aaa的样式
Copy after login

所以最后‘测试关于class的调用'几个字的样式是:font-size:50px; color:green;

2、这样的添加类方式很繁琐,每次添加一个新的,我还要带上之前写的类,容易带漏,并且还要检查是否带全,所以可以编写函数方法来解决添加类和删除类的问题:

function hasClass(element,className){   //判断是否存在类
    return element.className.match(new RegExp(&#39;(\\s|^)&#39;+className+&#39;(\s|$)&#39;));
 
}
//添加一个Class
function addClass(element,className){
  if(!hasClass(element,className)){
     element.className+=&#39; &#39;+className;
  }  
}  
//删除一个Class
function removeClass(element,className){
 if(hasClass(element,className)){
    element.className=element.className.replace
   (new RegExp(&#39;(\\s|^)&#39;+className+&#39;(\s|$)&#39;),&#39; &#39;);
 }
}
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用webpack如何实现文件打包

使用webpack如何实现文件打包

利用webpack搭建vue脚手架

使用Vue组件如何实现日历(详细教程)

The above is the detailed content of How to call class in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
js
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template