本文介绍了一个使用HTML、CSS和JavaScript实现的自定义走马灯效果。通过动态创建和填充图片数据,实现了无缝滚动的视觉体验。当鼠标悬停时停止滚动,离开时继续,提供了友好的交互。代码中详细展示了如何设置样式、布局以及JavaScript事件监听和动画处理,是前端开发中动态效果实现的一个实例。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>自定义走马灯</title> <style> #swipper { height: 360px; margin: 100px auto; overflow: hidden; } #swipper ul { height: 100%; padding: 0; margin: 0; position: relative; display: flex; } #swipper li { list-style: none; width: 600px; height: 100%; flex-shrink: 0; position: relative; transition: all 0.6s; box-sizing: border-box; z-index: 0; } #swipper li:hover { z-index: 1; transform: scale(1.2); } #swipper img { width: 100%; height: 100%; position: absolute; object-fit: cover; box-sizing: border-box; } </style> </head> <body> <div id="swipper"> <!-- type1 js插入节点 --> <ul></ul> <!-- type2 固定节点 --> <!-- <ul> <li> <img src="http://n.sinaimg.cn/photo/transform/700/w1000h500/20211002/658c-a8f83bea938d25b7c776d54bdfda3655.jpg" alt=""> </li> <li> <img src="http://n.sinaimg.cn/public_column/700/w1000h500/20211221/8666-7568268466f4f4cb06b4d6cf393e22b2.jpg" alt=""> </li> <li> <img src="http://n.sinaimg.cn/news/transform/700/w1000h500/20210316/51c0-kmkptxe0299440.jpg" alt=""> </li> <li> <img src="http://n.sinaimg.cn/photo/transform/700/w1000h500/20201106/1ad8-kcpxnwv8925892.png" alt=""> </li> </ul> --> </div> </body> <script> // js填充数据 let ulNode = document.querySelector('ul'); let imgArr = [{ id: 1, src: "http://n.sinaimg.cn/photo/transform/700/w1000h500/20211002/658c-a8f83bea938d25b7c776d54bdfda3655.jpg", }, { id: 2, src: "http://n.sinaimg.cn/public_column/700/w1000h500/20211221/8666-7568268466f4f4cb06b4d6cf393e22b2.jpg", }, { id: 3, src: "http://n.sinaimg.cn/news/transform/700/w1000h500/20210316/51c0-kmkptxe0299440.jpg", }, { id: 4, src: "http://n.sinaimg.cn/photo/transform/700/w1000h500/20201106/1ad8-kcpxnwv8925892.png", }, ] let li = ''; for (let x of imgArr) { li += `<li> <img src="${x.src}" key="${x.id}" /> </li>` } ulNode.innerHTML = li; // 走马灯实现效果 var oContainer = document.querySelector("#swipper"); var oWrapper = document.querySelector("ul"); var oSlide = document.querySelectorAll("li"); // 计算总宽度 var wrapperW = oSlide[0].offsetWidth * oSlide.length; // 复制一遍li总长度,实现无缝连接 oWrapper.style.width = wrapperW * 2 + "px"; oWrapper.innerHTML += oWrapper.innerHTML; if (wrapperW < oContainer.offsetWidth) { oContainer.style.width = wrapperW + "px"; } var i = 0, timer = null; var sliderMove = function() { timer = setInterval(function() { i++; if (i > wrapperW) { i = 0; } oWrapper.style.transform = 'translate(' + (-i) + 'px)'; }, 10) } sliderMove(); oContainer.addEventListener("mouseover", function() { clearInterval(timer); }) oContainer.addEventListener("mouseout", function() { sliderMove(timer); }) </script> </html>