利用纯js实现左右滑动、鼠标悬停暂停效果
css代码
<style> #scroll-container { width: 80%; overflow: hidden; margin: auto; white-space: nowrap; position: relative; } .scroll-content { display: inline-block; width: 100%; } /* 将广告项样式单独定义 */ .advert-item { display: inline-block; /* 或根据实际情况调整 */ } </style>
html代码
<div id="scroll-container"> <!-- 广告内容 --> <div id="scroll-content"> <!-- 实际广告项 --> <div class="advert-item"><img src="https://www.mimiwuqi.com/e/data/tmp/titlepic/f367b4dcbdc166b35d1922698038b1cf.png"></div> <div class="advert-item"><img src="https://www.mimiwuqi.com/e/data/tmp/titlepic/3b0ef68e909be8adc301cf8afd3aabeb.png" alt="css鼠标样式大全一览表"> </div> <div class="advert-item"><img src="https://www.mimiwuqi.com/e/data/tmp/titlepic/71ea0b93f98123c790bca9f071a018fd.png" alt="谷歌浏览器模拟百度ua蜘蛛访问"> </div> <div class="advert-item"><img src="https://www.mimiwuqi.com/e/data/tmp/titlepic/f367b4dcbdc166b35d1922698038b1cf.png"></div> <div class="advert-item"><img src="https://www.mimiwuqi.com/e/data/tmp/titlepic/3b0ef68e909be8adc301cf8afd3aabeb.png" alt="css鼠标样式大全一览表"> </div> <div class="advert-item"><img src="https://www.mimiwuqi.com/e/data/tmp/titlepic/71ea0b93f98123c790bca9f071a018fd.png" alt="谷歌浏览器模拟百度ua蜘蛛访问"> </div> <div class="advert-item"><img src="https://www.mimiwuqi.com/e/data/tmp/titlepic/f367b4dcbdc166b35d1922698038b1cf.png"></div> <div class="advert-item"><img src="https://www.mimiwuqi.com/e/data/tmp/titlepic/3b0ef68e909be8adc301cf8afd3aabeb.png" alt="css鼠标样式大全一览表"> </div> <div class="advert-item"><img src="https://www.mimiwuqi.com/e/data/tmp/titlepic/71ea0b93f98123c790bca9f071a018fd.png" alt="谷歌浏览器模拟百度ua蜘蛛访问"> </div> <!-- ... 更多广告项 ... --> </div> </div>
js代码
<script> document.addEventListener("DOMContentLoaded", function () { var scrollContainer = document.getElementById('scroll-container'); var scrollContent = document.getElementById('scroll-content'); var scrollAmount = 0; // 已滚动的量 var scrollSpeed = 1; // 每帧滚动的像素数 var itemWidth = scrollContent.offsetWidth; // 单个广告的宽度 var isScrolling = true; // 是否继续滚动的标志 // 增加内容以确保有足够的缓冲进行平滑滚动 // 假设您已经有了一个完全相同,用于平滑循环滚动的复制的内容 scrollContent.innerHTML += scrollContent.innerHTML; function step() { if (isScrolling) { // 更新滚动位置 scrollAmount += scrollSpeed; if (scrollAmount >= scrollContent.scrollWidth / 2) { // 重置滚动位置到最开始而非0 // 由于内容被复制过一份,所以是总宽度的一半 scrollAmount = 0; } scrollContainer.scrollLeft = scrollAmount; } // 继续动画 window.requestAnimationFrame(step); } // 启动动画 window.requestAnimationFrame(step); // 鼠标悬停时停止滚动 function stopScrolling() { isScrolling = false; } // 鼠标离开时恢复滚动 function startScrolling() { isScrolling = true; } // 添加鼠标事件监听器 scrollContainer.addEventListener('mouseover', stopScrolling); scrollContainer.addEventListener('mouseout', startScrolling); }); </script>
最终效果图: