获取样式和设置样式

<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')

最新文章

  1. Sublime Text 3 配置Java开发
  2. jquery层级原则器(匹配前一个元素后的所有平辈元素)
  3. Inheritance
  4. 代码分享:php对二维数组进行排序
  5. 认识C中的结构体
  6. 关于jQuery中.attr()和.prop()
  7. Gradle 1.12 翻译——第十四章. 教程 - 杂七杂八
  8. 剖析html对标准标签和自定义标签闭合与不闭合渲染问题
  9. jupyter notebooks 中键盘快捷键
  10. CDH 报错:under replicated blocks
  11. kibana Dev tool 查询结果与预期不符
  12. 「POJ-3608」Bridge Across Islands (旋转卡壳--求两凸包距离)
  13. Top useful .Net extension methods
  14. 【译】第39节---EF6-数据库命令日志
  15. Java使用点滴
  16. 【IT笔试面试题整理】连续子数组的最大和
  17. BZOJ1712 : [Usaco2007 China]Summing Sums 加密
  18. java enum 用法
  19. 【转】 Android定时器
  20. PAT 甲级 1146 Topological Order

热门文章

  1. FreeMarker基本使用
  2. HDU 1576 A/B(扩展欧几里德变形)
  3. 科普:alphago是什么
  4. Item 8:析构函数不要抛出异常 Effective C++笔记
  5. Hadoop作业性能指标及參数调优实例 (三)Hadoop作业性能參数调优方法
  6. mybits 操作指南
  7. oc23--变量修饰符
  8. Quartz实例:quartz定时任务代码示例
  9. 解决 dotnet core 1.x 命令行(cli) 下运行路径错误
  10. [HTML5] 新标签解释及用法