1.jQuery 样式操作
1.1 设置或者修改样式, 操作的是 style 属性.
单样式语法: jQuery 对象. CSS('属性名', '属性值')
- //html
- <div id="box"></div>
- //js
- $("#box").css("background","gray");// 将背景色修改为灰色
//js 代码运行完毕的结果
<div id="box" style="background: gray"></div>
设置多个样式:
- //html
- <div id="box"></div>
- //js
- $("#one").css({
- "background":"gray",
- "width":"400px",
- "height":"200px"
- });
- //js 执行完毕的结果
- <div id="box" style="background:gray; width:400px; height:200px"></div>
2 获取行内样式
- //html
- <div id="box" style="background: gray width:100px"></div>
- $("#box").css("background-color"); // 返回的是 rgb(128, 128, 128) --> gray
- $("#box").css("width"); // 返回 100px
2.1 操作 class 样式方式
- //html
- <div id="box"></div>
- //js
- $('#box').addClass('one');
- // 执行完之后的结果
- <div id="box" class="one"></div>
如果想要同时添加多个
- // 如果想要同时添加多个
- //html
- <div id="box"></div>
- //js
- $('#box').addClass('two three');
// 结果
<div id="box" class="two three"></div>
2.2 移除所有样式类
-1 如果不传参数, 那么会移除所有的类名
- //html
- <div id="box" class="one two three"></div>
- //js
- $('#box').removeClass();
- // 执行完毕的结果
- <div id="#box" class></div>
-2 如果传入参数, 删除指定的类名
- //html
- <div id="box" class="one two three"></div>
- //js
- $('#box').removeClass('one');
- // 执行完毕的结果
- <div id="#box" class="two three"></div>
- //======================================================================================
- // 如果想同时删除多个类名
- //html
- <div id="box" class="one two three"></div>
- //js
- $('#box').removeClass('one three');
- // 结果
- <div id="#box" class="two"></div>
-3 判断是否有样式类
- //html
- <div id="box" class="one"></div>
- //js
- $('#box').hasClass('one'); // 返回 true
- $('#box').hasClass('two'); // 返回 false
-4 切换样式类
如果有这个类名, 则移除该样式, 如果没有, 添加该类名.
- //html
- <div id="box"></div>
- //js
- $('#box').toggleClass('one');
- // 执行完的结果
- <div id="box" class="one"></div>
- // 此时再执行一次 toggleClass('one');
- $('#box').toggleClass('one');
- // 执行完的结果
- <div id="box" class></div>
3 jQuery 中的隐式迭代: jQuery 内部会帮我们遍历 DOM 对象, 然后给每一个 DOM 对象实现具体的操作.
来源: http://www.bubuko.com/infodetail-2615181.html