我查了非常多的资料,但都是不能够实现,因为一些细节上的和兼容性上的问题。在请教了ChatGPT老师后终于找到了解决方法。同时不影响鼠标快停的效果实现。
这是我的部分页面元素:
<div class="container mx-auto px-10 md:px-20 duration-500 p-10">
<div
class="rounded-lg mx-auto flex flex-row justify-start mx-w-xl shadow-lg bg-gradient-to-r from-green-400 to-blue-500 snap-x fixed inset-20 overflow-x-auto scroll-pl-40 overscroll-none snap-mandatory"
id="scroll-container"
>
<div
class="snap-center rounded-lg h-auto p-5 m-5 text-blue-200 text-4xl w-4"
></div>
<div
class="snap-always snap-center rounded-lg h-auto bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 p-5 m-5 text-blue-200 text-4xl aspect-video"
>
<p>组长-</p>
<br />
<p>简介:爱好-玩原神</p>
</div>
<div
class="snap-always snap-center rounded-lg h-auto bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 p-5 m-5 text-blue-200 text-4xl aspect-video"
>
<p>组员-</p>
<br />
<p>简介:爱好-玩原神</p>
</div>
<div
class="snap-always snap-center rounded-lg h-auto bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 p-5 m-5 text-blue-200 text-4xl aspect-video"
>
<p>组员-</p>
<br />
<p>简介:爱好-玩原神</p>
</div>
<div
class="snap-always snap-center rounded-lg h-auto bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 p-5 m-5 text-blue-200 text-4xl aspect-video"
>
<p>组员-</p>
<br />
<p>简介:爱好-玩原神</p>
</div>
<div
class="snap-center rounded-lg h-auto p-5 m-5 text-blue-200 text-4xl w-4"
></div>
</div>
</div>
把没用的部分折叠一下:
<div class="container mx-auto px-10 md:px-20 duration-500 p-10">
<div
class="flex flex-row justify-start
snap-x fixed inset-20 overflow-x-auto
scroll-pl-40 overscroll-none snap-mandatory"
id="scroll-container"
>
<div class="snap-center w-4"></div>
<div class="snap-always snap-center">
...
</div>
<div class="snap-always snap-center">
...
</div>
<div class="snap-always snap-center">
...
</div>
<div class="snap-always snap-center">
...
</div>
<div class="snap-center w-4"></div>
</div>
</div>
我用了tailwindcss来定义样式,但是不影响讲解。总之这个#scroll-container,是横向滚动的,并且有快停效果
查了很多资料都没用,我估计是edge受到快停的影响,导致鼠标滚动后一直吸附到原位,这是解决方案:
<script>
document.addEventListener('DOMContentLoaded', function () {
const scrollContainer = document.getElementById('scroll-container');
// 添加滚轮事件监听器
scrollContainer.addEventListener('wheel', function (event) {
// 阻止默认的垂直滚动
event.preventDefault();
// 根据滚轮滚动的距离,调整横向滚动条的位置
// !!注!!:如果没有快停效果,可以尝试这个:
// scrollContainer.scrollLeft += event.deltaY;
// 或者,你也可以使用 scrollBy 方法
// !!兼容快停效果的解决方案:
scrollContainer.scrollBy({ left: event.deltaY, behavior: 'smooth' });
});
});
</script>
对于scrollContainer.scrollLeft += event.deltaY;这个方法,如果滚动距离不够,可以*2,*3之类。
把我的js的变量名和选择器改成你们的就行
效果: