How to call class in JavaScript
Jun 23, 2018 pm 06:11 PM下面小编就为大家带来一片JavaScript中关于class的调用方法。具有很好的参考价值,希望对大家有所帮助
PS:class的调用,其实是可以叠加的,当然了这要求样式不同的情况下,如果样式相同,则后一个样式会覆盖前一个样式。
1、举例如下:
<p id="test" class="aaa bbb">测试关于class的调用</p>
.aaa{ font-size:20px; color:red; } .bbb{ font-size:50px; color:green; }
var test=document.getElementById('test'); test.className='aaa'; test.className='aaa bbb';//因为aaa和bbb的样式相同,所以,bbb的样式会覆盖aaa的样式
所以最后‘测试关于class的调用'几个字的样式是:font-size:50px; color:green;
2、这样的添加类方式很繁琐,每次添加一个新的,我还要带上之前写的类,容易带漏,并且还要检查是否带全,所以可以编写函数方法来解决添加类和删除类的问题:
function hasClass(element,className){ //判断是否存在类 return element.className.match(new RegExp('(\\s|^)'+className+'(\s|$)')); } //添加一个Class function addClass(element,className){ if(!hasClass(element,className)){ element.className+=' '+className; } } //删除一个Class function removeClass(element,className){ if(hasClass(element,className)){ element.className=element.className.replace (new RegExp('(\\s|^)'+className+'(\s|$)'),' '); } }
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use JS and Baidu Maps to implement map pan function

Recommended: Excellent JS open source face detection and recognition project

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts

How to create a stock candlestick chart using PHP and JS

How to use JS and Baidu Maps to implement map polygon drawing function

How to use JS and Baidu Map to implement map click event processing function
