var img1 = document.getElementById("img1"); var pre = document.getElementById("pre"); var next = document.getElementById("next"); var lilist = document.getElementsByTagName("li"); var imgsrc = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg", "img/5.jpg"]; var i = 0;setInterval(changeimg, 3000); function changeimg() { i++; if (i >= imgsrc.length) { i = 0; } img1.setAttribute("src", imgsrc[i]); addcirclebg(); } function addcirclebg() { for (var k = 0; k < lilist.length; k++) { if (k == i) { lilist[k].className = "bgcolor"; } else { lilist[k].className = ""; } } } next.onclick = changeimg; pre.onclick = function () { i--; if (i < 0) { i = imgsrc.length - 1; } img1.setAttribute("src", imgsrc[i]); addcirclebg(); }; for (var j = 0; j < lilist.length; j++) { lilist[j].setAttribute("index", j); lilist[j].onclick = function () { var a = this.getAttribute("index"); console.log(a); img1.setAttribute("src", imgsrc[a]); for (var k = 0; k < lilist.length; k++) { if (lilist[k] == this) { this.className = "bgcolor"; } else { lilist[k].className = "";}}};}添加注释
时间: 2023-06-24 22:05:16 浏览: 117
// 获取页面元素
var img1 = document.getElementById("img1");
var pre = document.getElementById("pre");
var next = document.getElementById("next");
var lilist = document.getElementsByTagName("li");
// 图片路径数组
var imgsrc = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg", "img/5.jpg"];
// 当前显示的图片下标
var i = 0;
// 切换图片函数
setInterval(changeimg, 3000);
function changeimg() {
i++;
if (i >= imgsrc.length) {
i = 0;
}
img1.setAttribute("src", imgsrc[i]);
addcirclebg();
}
// 改变圆点背景色函数
function addcirclebg() {
for (var k = 0; k < lilist.length; k++) {
if (k == i) {
lilist[k].className = "bgcolor";
} else {
lilist[k].className = "";
}
}
}
// 绑定上一张、下一张图片切换事件
next.onclick = changeimg;
pre.onclick = function () {
i--;
if (i < 0) {
i = imgsrc.length - 1;
}
img1.setAttribute("src", imgsrc[i]);
addcirclebg();
};
// 绑定圆点点击事件
for (var j = 0; j < lilist.length; j++) {
lilist[j].setAttribute("index", j);
lilist[j].onclick = function () {
var a = this.getAttribute("index");
console.log(a);
img1.setAttribute("src", imgsrc[a]);
for (var k = 0; k < lilist.length; k++) {
if (lilist[k] == this) {
this.className = "bgcolor";
} else {
lilist[k].className = "";
}
}
};
}
阅读全文