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