jQuery addClass
时间:2020-02-23 14:46:03 来源:igfitidea点击:
jQuery addClass函数用于将一个或者多个指定的类添加到匹配的DOM元素中。
jQuery addClass
这是一个简单的示例,显示了jQuery addClass()方法的用法。
示例中使用的jQuery版本是3.2.1。
<html> <head> <!-- import jQuery library --> <script type="text/javascript" src="jquery-3.2.1.min.js"></script> <!-- jQuery functions for addClass example --> <script type="text/javascript"> $(function() { $("p:last").addClass("selected highlight"); }); $(function() { $("p:first").addClass("highlight"); }); </script> <style> p { margin: 10px; font-size: 16px; } .selected { color: maroon; } .highlight { background: yellow; } </style> </head> <body> <p>hyman</p> <p>Kumar</p> <p>Bye</p> </body> </html>
在jQuery addClass函数中,我们将" selected"和" highlight"类添加到元素" p:last"。
同样,我们在" p:first"中添加了" highlight"类。
因此,在页面加载时,这些类将应用于<p>的第一个和最后一个孩子,并且html会被格式化。
下图显示了在浏览器中输出的jQuery addClass示例HTML页面。
斑马条纹效果的jQuery addClass示例
我们使用jQuery addClass()方法在HTML表中创建斑马条纹效果。
html代码如下。
<html> <head> <title>jQuery addClass Example - Table Zebra Stripes</title> </head> <script type="text/javascript" src="jquery-3.2.1.min.js"></script> <!-- jQuery script to check if row is even, addClass is used to add CSS class to the row --> <script type="text/javascript"> $(function() { $("table tr:nth-child(even)").addClass("striped"); }); </script> <!-- Below CSS is used for configuring table display --> <style type="text/css"> body,td { font-size: 12px; } table { background-color: black; border: 1px black solid; border-collapse: collapse; } th { border: 1px outset silver; background-color: blue; color: white; } tr { border: 1px outset silver; background-color: white; margin: 1px; } tr.striped { border: 1px outset silver; background-color: yellow; } td { padding: 1px 10px; } </style> <body> <table> <tr> <th>ID</th> <th>Name</th> <th>Role</th> </tr> <tr> <td>1</td> <td>hyman</td> <td>CEO</td> </tr> <tr> <td>2</td> <td>Lisa</td> <td>Manager</td> </tr> <tr> <td>3</td> <td>Robin</td> <td>Support</td> </tr> <tr> <td>4</td> <td>David</td> <td>Editor</td> </tr> </table> </body> </html>
在上面HTML中,我们使用条件table tr:nth-child(even)
动态地向表行的每个偶数子级添加" striped"类。