Home > Web Front-end > JS Tutorial > How to call class in JavaScript

How to call class in JavaScript

小云云
Release: 2018-05-23 09:15:31
Original
4251 people have browsed it

class的调用,其实是可以叠加的,当然了这要求样式不同的情况下,如果样式相同,则后一个样式会覆盖前一个样式。本文我们就和大家分享JavaScript中关于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

相关推荐:

html中规定元素的类名的属性class

HTML5的classList属性操作CSS类的使用详解

css中三种样式的方法(id,class,style)的实例分析

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:
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