HTML+JQuery+Tailwind滚动画廊活跃元素未居中的精准偏移方案
精准实现活跃图片居中的解决方案
你当前的偏移计算逻辑存在问题,错误使用了scrollContainer的宽度来推导中心位置,导致无法精准对齐视口中心。以下是修正后的实现方案:
修正后的jQuery代码
$(document).ready(function() { const scrollContainer = $("#scrollContainer"); const divs = scrollContainer.children("div"); const gap = 20; // 对应flex容器的gap-x-20 let divWidth = divs.first().width(); let currentIndex = 0; function updateDivs() { divs.each(function(index, element) { const isActive = index === currentIndex; const height = isActive ? 450 : 350; const blur = isActive ? "blur(0)" : "blur(5px)"; const opacity = isActive ? 1 : 0; $(element).css({ height: `${height}px`, filter: blur, }).find(".text-white").css("opacity", opacity); }); // 精准计算居中偏移 const viewportWidth = $(window).width(); // 活跃元素中心相对于scrollContainer的偏移量 const activeElementCenterOffset = currentIndex * (divWidth + gap) + divWidth / 2; // 视口中心位置 const viewportCenter = viewportWidth / 2; // 计算scrollContainer需要移动的距离,让两者中心对齐 const scrollOffset = viewportCenter - activeElementCenterOffset; scrollContainer.css("transform", `translateX(${scrollOffset}px)`); } $("#rightScroll").click(function() { currentIndex = Math.max(currentIndex - 1, 0); updateDivs(); }); $("#leftScroll").click(function() { currentIndex = Math.min(currentIndex + 1, divs.length - 1); updateDivs(); }); // 窗口尺寸变化时重新计算元素宽度,适配响应式布局 $(window).resize(function() { divWidth = divs.first().width(); updateDivs(); }); updateDivs(); });
关键修正说明
- 拆分宽度计算:将元素自身宽度和flex gap分开定义,避免原代码中宽度与间距混淆的问题,确保偏移计算精准。
- 基于视口对齐:直接以视口宽度的一半作为目标中心,计算活跃元素当前的中心位置,通过
translateX让两者严格对齐。 - 添加resize监听:由于元素宽度使用了
calc(100vw*0.65)的响应式设置,窗口尺寸变化时会改变元素宽度,需重新计算并更新布局。
可选HTML优化(非必须)
可以将内联样式中的重复属性提取为Tailwind自定义类,让代码更整洁:
<!-- 在tailwind配置中添加自定义类 --> <!-- theme: { extend: { width: { 'project-card': 'calc(100vw*0.65)', }, height: { 'project-active': '450px', 'project-inactive': '350px', } } } --> <div class="flex flex-shrink-0 flex-col justify-end h-project-inactive blur-md w-project-card p-6 box-border rounded-[1.25rem] bg-[linear-gradient(35deg,rgba(0,0,0,1)_0%,rgba(0,0,0,0.8)_20%,rgba(130,130,130,0.2)_60%,rgba(130,130,130,0.2)_100%)] bg-cover bg-no-repeat bg-center"> <span class="uppercase text-white text-4xl font-normal opacity-0">Health Tech Website</span> </div>
内容的提问来源于stack exchange,提问作者NATHAN TOLLEY
相关产品推荐
相关产品推荐

