代码
提交代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> </head> <body> <style> .container {position: fixed;top: 0;bottom: 0;right: 0;left: 0;background-color: rgba(0, 0, 0, .7);} .container .swiper-pagination {display: none;} .slide-item {overflow: hidden;} .slide-item img {width: 100%;} .count {position: absolute;left: 50%;transform: translateX(-50%);top: 16px;color: white;} </style> <link href="https://cdn.bootcdn.net/ajax/libs/Swiper/5.4.5/css/swiper.min.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/Swiper/5.4.5/js/swiper.min.js"></script> <script> function previewImage(current, list) { if (!list) list = [current]; // 如果没传,默认以初始图为列表 if (list.length === 0) list = [current]; // 如果数组为空 则以初始图为列表 var idx = 0; // 寻找初始图在列表的位置 var html = list.map(function(item, index) { if (item === current) { // 如果两个图 url 相等,则说明初始图就是在这个位置 idx = index + 1; // 记录下位置 } // 拼一个 swiper-slide return [ '<div class="swiper-slide slide-item">', '<div class="swiper-zoom-container">', // 应用缩放配置项要提供这个节点 '<img src="' + item + '" />', '</div>', '</div>', ].join(''); }); var wrapper = document.createElement('div'); // 创建一个 swiper-wrapper wrapper.className = 'swiper-wrapper'; wrapper.innerHTML = html.join(''); // 把所有 swiper-slide 塞进去 var container = document.createElement('div'); // 创建跟节点 container.className = 'container'; // 把所有 html 拼起来 container.innerHTML = [ '<div class="count">', '<span class="current">' + (idx || 1) + '</span>', '/', '<span class="total">' + list.length + '</span>', '</div>', wrapper.outerHTML, '<div class="swiper-pagination"></div>', ].join(''); // 添加到 DOM 中 document.body.appendChild(container); // 实例化一个 swiper new Swiper(container, { zoom: true, // 缩放开启 loop: list.length > 1, // 如果图片只有一张,则不开启循环 pagination: { // 分页配置 el: '.swiper-pagination', }, on: { // 事件监听 paginationUpdate: function(e) { // 当分页发生变化的时候 var idx = e.realIndex; // 拿到当前页索引 // 赋值给分页计数器 container.querySelector('.current').innerText = idx + 1; }, }, }).slideTo(idx, 0); // 默认展示初始图 } previewImage('https://img.mukewang.com/5ef94c8e000109e118720764.jpg', [ 'https://img.mukewang.com/5f057a6a0001f4f918720764.jpg', 'https://img.mukewang.com/5ef94c8e000109e118720764.jpg', 'https://img.mukewang.com/5ef15e4e00010b0018720764.jpg', 'https://img.mukewang.com/5f0561160001630718720764.jpg', ]); </script> </body> </html>
运行结果