批改状态:合格
老师批语:
<div class="slideshow"><!-- 1. 图片容器 --><div class="imgs"></div><!-- 2. 按钮容器 --><div class="btns"></div></div><script type="module">// 1.获取图片容器和按钮容器const imgs = document.querySelector(".imgs");const btns = document.querySelector(".btns");// 2.导入轮播图模板import {createImgs,createBtns,switchImg,timePlay,} from "./static/js/slideshow.js";window.onload = () => {// (1)创建图片组createImgs(imgs);// (2)创建按钮组createBtns(imgs, btns);// (3)创建按钮事件[...btns.children].forEach(function (btn) {btn.onclick = function () {switchImg(this, imgs);};});// (4)定时器// 按钮数组const btnArr = [...btns.children];const btnKeys = Object.keys(btns.children);setInterval(function (btnArr, btnKeys) {timePlay(btnArr, btnKeys);},2000,btnArr,btnKeys);};</script>
// todo 轮播图模块// * 1.图片组const imgArr = [{key: 1,src: "static/images/1.jpg",url: "https://php.cn",},{key: 2,src: "static/images/2.jpg",url: "https://php.cn",},{key: 3,src: "static/images/3.jpg",url: "https://php.cn",},];// * 2.创建图片组function createImgs(imgs) {const frag = new DocumentFragment();for (let i = 0; i < imgArr.length; i++) {// 创建图片元素// const img = document.createElement("img");const img = new Image();// 2.添加属性img.src = imgArr[i].src;img.dataset.key = imgArr[i].key;if (i === 0) img.classList.add("active");// 3.添加事件img.onclick = () => (location.href = imgArr[i].url);frag.append(img);}imgs.append(frag);}// 3.创建按钮组function createBtns(imgs, btns) {let length = imgs.childElementCount;for (let i = 0; i < length; i++) {// 1.生成按钮const btn = document.createElement("span");// 2.按钮索引btn.dataset.key = imgs.children[i].dataset.key;// 3.第一个按钮激活if (i === 0) btn.classList.add("active");// 4.添加到容器中btns.append(btn);}}// 4.按钮点击事件function switchImg(btn, imgs) {// 1. 去掉图片和按钮的激活状态[...btn.parentNode.children].forEach(btn => btn.classList.remove("active"));[...imgs.children].forEach(img => img.classList.remove("active"));// 2. 将当前的按钮处于激活状态btn.classList.add("active");// 3. 根据按钮索引,找到对应的图片const currImg = [...imgs.children].find(function (img) {return img.dataset.key == btn.dataset.key;});// const currImg = [...imgs.children].find(img => img.dataset.key == btn.dataset.key);// console.log(currImg);// 4. 将当前图片处于激活状态(显示出来)currImg.classList.add("active");}// 5.定时播放function timePlay(btnArr, btnKeys) {let key = btnKeys.shift();btnArr[key].dispatchEvent(new Event("click"));btnKeys.push(key);}export { createImgs, createBtns, switchImg, timePlay };

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号