1. 两个单击事件完成图片的切换
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>单击事件</title>
</head>
<body>
<button id="a" title="red">图片点击1</button>
<button id="bn" title="black">图片点击2</button>
<button id="bd">点击演示3</button>
<br>
<img src="./images/1001.jpg" alt="" title="">
<script>
//title="red" 鼠标放在点击按钮显示文字
//获取元素
let aa=document.getElementById("a")
let bb=document.getElementById("bn")
let img=document.querySelector('img')
let bd=document.getElementById('bd')
//修改元素点击事件
aa.onclick=function(){
img.src="./images/1001.jpg"
img.title="r" //鼠标放在图片显示文字
}
//可以看到getElementById只能绑定一个事件bb.onclick=function(){} 如果后面相同事件则覆盖前面的事件,因此可以使用addEventListener
bb.onclick=function(){
img.src="./images/timg.jpg"
img.title="b" //鼠标放在图片显示文字
}
bd.addEventListener("click",function(){
alert("1")
})
bd.addEventListener("click",function(){
alert("2")
})
bd.addEventListener("click",function(){
alert("3")
})
</script>
</body>
</html>
图片的切换以及xx.οnclick=function(){} 与 addEventListener()绑定事件
2.手动切换几张图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> 手动切换图片</title>
<style>
.body{
margin: auto;
}
.outer{
text-align: center;
}
img{
width: 40%;
height: 40%;
margin:50px auto;
}
p{
margin: 20px;
font-weight: bold;
}
</style>
<script>
window.onload=function(){
//获取img
const img=document.getElementsByTagName("img")[0]
//获取标签
const ifoc=document.getElementById("ifoc")
//获取按钮
const prev=document.getElementById("prve")
const nextt=document.getElementById("next")
//创建数组存图片路径
const imgas=["./images/1001.jpg",
"./images/timg.109.jpg",
"./images/timg.jpg",
"./images/timg102.jpg",
"./images/timg105.jpg",
"./images/timg698.jpg",
]
//创建变量记录图片索引
let bian=0
ifoc.textContent=`一共${imgas.length}张图片当前是第${bian+1}张图片`
nextt.onclick=function(){
bian-- //计算索引>0 and <5
if (bian<0){ //最小不能<0
bian=imgas.length-1 //也就是将数组的最大值赋给记录索引
}
img.src=imgas[bian]
ifoc.textContent=`一共${imgas.length}张图片当前是第${bian+1}张图片`
}
prev.onclick=function(){
bian++ //计算索引>0 and <5
if (bian>imgas.length-1){ //最大不能>5
bian=0 //也就是将数组的最小值值赋给记录索引
}
img.src=imgas[bian]
ifoc.textContent=`一共${imgas.length}张图片当前是第${bian+1}张图片`
}
}
</script>
</head>
<body>
<div class="outer">
<div class="img-wap">
<img src="./images/timg102.jpg">
</div>
<p id="ifoc">
</p>
<div class="btn-wap">
<button id="prve">上一张</button>
<button id="next">下一张</button>
</div>
</div>
</body>
</html>
用于少数的图片,做一个切换
记得复习!