有时候需要添加 CSS 样式和移除 CSS 样式, 如添加 display 属性, 设为隐藏; 有时候需要移除 display 属性. 下面本篇文章就来给大家介绍一下 JS/jQuery 删除 CSS 样式的方法.
jQuery 移除 CSS 样式的两种方法
注意: 当其中一种不支持时, 就尝试另一种:
- $("#show").removeAttr("style");
- $("#show").toggleClass("style")
removeAttr() 方法从被选元素中移除属性.
语法
$(selector).removeAttr(attribute)
attribute: 必需. 规定从指定元素中移除的属性.
toggleClass() 方法对添加和移除被选元素的一个或多个类进行切换.
该方法检查每个元素中指定的类. 如果不存在则添加类, 如果已设置则删除之. 这就是所谓的切换效果.
然而, 通过使用 "switch" 参数, 您能够规定只删除或只添加类.
语法
$(selector).toggleClass(classname,function(index,currentclass),switch)
classname 必需. 规定添加或移除的一个或多个类名. 如需规定若干个类, 请使用空格分隔类名.
function(index,currentclass) 可选. 规定返回需要添加 / 删除的一个或多个类名的函数. index - 返回集合中元素的 index 位置. currentclass - 返回被选元素的当前类名.
switch 可选. 布尔值, 规定是否仅仅添加 (true) 或移除 (false) 类.
示例 1:
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="utf-8">
- <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
- </script>
- <script>
- $(document).ready(function() {
- $("button").click(function() {
- $("p").removeAttr("style");
- });
- });
- </script>
- </head>
- <body>
- <h1>
- 这是一个标题
- </h1>
- <p style="font-size:120%;color:red">
- 这是一个段落.
- </p>
- <p style="font-weight:bold;color:blue">
- 这是另一个段落.
- </p>
- <button>
- 移除所有 P 元素的样式属性
- </button>
- </body>
- </HTML>
效果图:
示例 2:
- <!DOCTYPE HTML>
- <HTML>
- <head>
- <meta charset="utf-8">
- <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
- </script>
- <script>
- $(document).ready(function() {
- $("button").click(function() {
- $("p").toggleClass("main");
- });
- });
- </script>
- <style>
- .main{ font-size:120%; color:red; }
- </style>
- </head>
- <body>
- <button>
- 转换 P 元素的 "main" 类
- </button>
- <p>
- 这是一个段落.
- </p>
- <p>
- 这是另一个段落.
- </p>
- <p>
- <b>
- 注意:
- </b>
- 单击按钮查看多次切换的效果.
- </p>
- </body>
- </HTML>
效果图:
来源: http://www.css88.com/qa/jquery/13373.html