jQuery样式操作

 

获取样式和设置样式

<p class='myClass'  title='this is p'>this is p</p>

样式其实就是class属性所以设置和获取样式都能用attr()方法来完成,attr()方法用法:http://www.cnblogs.com/kuangxin/p/4243991.html


追加样式

实例:

<style>

  .high{

      font-weight:bold;//字体加粗

      color:red;//字体颜色设置为红色

     }

  .another{

      font-style:italic;//斜体

      color:blue;//字体设置为蓝色

          }

</style>

<p class="high" title="this is p">this is p</p>

jQuery代码:

$(p).addClass('another');

结果:

<p class="hight another" title="this is p">this is p</p>

此时在<p>元素中同时拥有俩个class值,即‘hight’和‘another’。在css中有以下俩条规定:

(1)如果给一个元素添加了多个class值,那么就相当于合并了他们的样式。

(2)如果不同的class设定了同一样式属性,则后者覆盖前者。

在上例中相当于给<p>元素添加了如下样式:

      font-weight:bold;//字体加粗

      color:red;//字体颜色设置为红色

      font-style:italic;//斜体

      color:blue;//字体设置为蓝色

在以上样式中,存在两个‘color’属性,而后面的‘color’属性会覆盖前面的‘color’属性,因此最终的’color‘属性的值为’blue‘,而不是’red‘,样式最终呈现为:

      font-weight:bold;//字体加粗

      font-style:italic;//斜体

      color:blue;//字体设置为蓝色

attr和addClass()的区别:

<p>this is p<p>

$('p').addClass('high');//结果<p class='high'>this is p</p>

$('p').attr('class','high');//结果<p class='high'>this is p<p>

再次使用

$('p').addClass('another');//结果<p class='high another'>this is p</p>

$('p').attr('class','another');//结果<p class='another'>this is p<p>


 

移除样式

实例:

HTML:

<p class='high another'>this is p</p>

jQuery代码:

$('p').removeClass('high');//移除high样式

$('p').removeClass('another');//移除another样式

等价于

$('p').removeClass('high anothe');//移除high another样式

等价于

$('p').removeClass();//清空样式

结果:

<p>this is p</p>


切换样式

HTML:

<p class='myClass'>this is p</p>

jQuery代码:

$('p').toggleClass('another');//切换为another样式

注意!       toggleClass()方法会不停的在俩种样式之间切换,当class为myClass时,运行代码则切换为another,当class为another时,运行代码则切换为myClass


 

判断是否包含某个样式

jQuery代码:

var bool= $('p').hasClass('myClass');//判断p标记是否包含样式myClass,包含返回true,否则返回false

注意!      这个方法是为了增强代码可读性而产生的,在jQuery内部实际上是调用了is()方法来完成这个功能的,上述代码等价于var bool=$('p').is('.myClass')

 

posted @ 2015-01-23 13:55  逗比浪波万  阅读(279)  评论(0编辑  收藏  举报