1.DOM基础
1.获取DOM元素
document.querySelector()
document.querySelectorAll()
形参为"abc" -> 绑定第一个 <abc></abc> 这一对标签
形参为".abc"-> 绑定第一个class="abc"的标签
形参为"#abc"-> 绑定第一个id="abc"的标签
2.用className更换标签的 class 属性
<style>
.active{
background-color: orangered;
}
</style>
<h1 class="abc"> HELLO </h1>
<h1 class="abc"> HELLO </h1>
<h1 class="abc"> HELLO </h1>
<h1 class="abc"> HELLO </h1>
<h1 class="abc"> HELLO </h1>
<script>
let h1List = document.querySelectorAll("h1")
for (let i in h1List){
h1List[i].onclick = function(){
if(h1List[i].className === "active"){
h1List[i].className = "abc"
}else{
h1List[i].className = "active"
}
}
}
</script>
2.案例 实现轮播图
<style type="text/css">
.swiper{
width: 40rem;
height: 20rem;
overflow: hidden;
position: relative;
}
.img-container{
width: 120rem;
height: 20rem;
display: flex;
transition: 0.5s;
}
.img-container img{
width: 40rem;
height: 20rem;
}
.number-list{
position: absolute;
bottom: 0;
}
</style>
<div class="swiper">
<div class="img-container">
<img class="img" src="img/1.jpg" />
<img class="img" src="img/2.png" />
<img class="img" src="img/3.png" />
</div>
<div class="number-list">
<button>1</button>
<button>2</button>
<button>3</button>
</div>
</div>
let btns = document.querySelectorAll(".number-list button")
let container = document.querySelector(".img-container")
for(let i in btns){
btns[i].onclick = function(){
container.style.transform = `translate(${-40*i}rem)`
}
}