JavaScript之图片切换功能
为了实现如下图片构造(点击上一张显示上一张图片,点击下一张显示下一张图片),我们写了如下代码:
图片切换
/*控制图片大小*/
#flower{
width: 200px;
height: 300px;
}
上一张
下一张
// 1.获取事件源 需要的标签
var flower = document.getElementById("flower");
var nextBtn = document.getElementById("next");
var prevBtn = document.getElementById("prev");
// 共四张图,定义范围最小1,最大4,默认为1
var minIndex = 1;maxIndex = 4;currentIndex = minIndex;
// 2.监听按钮的点击
nextBtn.onclick = function (){
if (currentIndex === maxIndex) {
// 到最后一张了
currentIndex = minIndex;
}else {
currentIndex++;
}
flower.setAttribute("src", `img/image0${currentIndex}.jfif`);
}
prevBtn.onclick = function (){
if (currentIndex === minIndex) {
// 到最后一张了
currentIndex = maxIndex;
}else {
currentIndex--;
}
// 注:setAttribute()的功能是把指定的属性设置为指定的值。如果不存在具有指定名称的属性,该方法将创建一个新属性。
flower.setAttribute("src", `img/image0${currentIndex}.jfif`);
}
实结果如下: 点击上一张的按钮会跳转上一张,比如这样: 简单的图片切换效果就实现啦! 觉得有用的话可以给作者鼓励支持一下~你的鼓励就是我不断前行的动力!
|