添加类样式方法
addClass():向被选元素添加指定的类名
注意:该方法仅仅只是在原有基础上添加属性,不会覆盖已存在的 class 属性
提示:如需添加多个类,使用空格分隔类名
一、添加一个class属性
<style>
.div {
width: 200px;
height: 200px;
background-color: pink;
}
.style {
width: 300px;
background-color: yellow;
border: greenyellow 5px solid;
}
</style>
<body>
<div class="div"></div>
</body>
<script>
$('.div').addClass('style')
</script>
通过元素选择发现style成功追加在了div的后面
结果
二、这时候如果将div和style属性的定义顺序调换后,就出现了问题
<style>
.style {
width: 300px;
background-color: yellow;
border: greenyellow 5px solid;
}
.div {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
<body>
<div class="div"></div>
</body>
<script>
$('.div').addClass('style')
</script>
发现背景颜色和宽度并没有改变,复习css的样式覆盖规则后知道了问题所在
样式冲突时,样式权值高者获胜
样式权值相同时,后定义者获胜
权值定义如下:
CSS选择器 | 权值 |
---|---|
标签选择器 | 1 |
类选择器 | 10 |
ID选择器 | 100 |
内联样式 | 1000 |
伪元素(:first-child等) | 1 |
伪类(:link等) | 1 |
很明显,这里样式发生了冲突,并且权值一样,所以看定义顺序
div在style后定义故页面渲染了div的样式
三、添加多个class属性
<style>
.div {
width: 200px;
height: 200px;
background-color: pink;
}
.style {
width: 300px;
background-color: yellow;
border: greenyellow 5px solid;
}
.text {
color: brown;
font-size: 30px;
text-align: center;
}
</style>
<body>
<div class="div">addClass</div>
</body>
<script>
$('.div').addClass('style text')
</script>