1.基本CSS选择器分为:
①元素选择器:
②属性选择器:属性选择器是对元素选择器更精确地限制,所有的html属性都可以作为限制条件,不仅仅是id属性
③ID选择器;
④Class选择器:
⑤.包含选择器:
⑥子选择器:
⑦兄弟选择器(不常用):平级下寻找后面的兄弟元素(只找弟弟,不找哥哥)
⑧选择器组合:Selector1,Selector2,Selector3.......
2.伪元素CSS选择器:
①. :first-letter:
②. :before
after跟before同理,只不过是在已有元素后面插入内容
3.伪类CSS选择器
1.结构性伪类选择器:
nth-child(n)此中的n,可以是1,2...也可以是odd(奇数) | even(偶数) | 表达式,比如2n+1
注意:nth-child(n),当不是表达式的时候,n是从1开始的;当是表达式的时候,是从0开始
2.其他伪类选择器:
:not() 代表过滤掉某个或某些元素
注意:如果想排除多个元素,应该这样书写选择器Selector1:not(Selector2):not(Selector3)...
4. CSS选择器优先级规则(重要)
规则1:
选择器写的越准确(越长),优先级越高
规则2:
优先级高低:ID选择器>class选择器>元素选择器
规则3:
同级别同长度下,css代码按照顺序执行,后面的代码把前面的代码覆盖,即样式效果覆盖
规则4(终极规则):
以上规则适用绝大部分场景,若特殊场景不适用时,自行测试
5.脚本修改CSS样式
注意:脚本中的css属性书写时,要按照驼峰写法书写,例如:静态css中的background-color,在脚本中要写成backgroundColor。
代码片段:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>选择器</title>
<style>
.ld {
color: red;
background-color: blue;
font-size: 50px;
}
</style>
</head>
<body id="bg">
<h3 id="ld">ld</h3>
<h3 id="zaq">zaq</h3>
<script>
var obj = document.getElementById("zaq")
var obj1 = document.getElementById("ld")
console.log(obj);
//obj.style.属性 = 属性值
obj.style.color = "red";
obj.style.fontSize = "50px";
//定义函数
function change() {
var bg = "";
for (var i = 0; i < 6; i++) {
bg = bg + Math.round(Math.random() * 9)
}
alert(123)
document.getElementById("bg").style.background = "#" + bg;
//obj.style.background = "blue";
//obj.style.color = "red";
//obj.style.fontSize = "50px";
obj1.className = "ld"
}
//点击交互
obj.onclick = change
</script>
</body>
</html>
运行结果:
第一步
第二步
第三步:接着点击zaq区域会继续弹出提示框点击确定,背景会发生变化:代码图为: