如何用TailwindCSS修改MarqueeBanner实现文字跨屏滚动?
问题分析
当前代码的核心问题是:滚动文本的容器宽度仅匹配内容宽度,动画无法覆盖整个屏幕;关闭按钮随文本滚动,不符合交互预期。需要调整DOM结构、定位逻辑和动画参数来实现目标效果。
修改方案
1. 调整组件DOM结构与样式
将关闭按钮改为绝对定位,避免随文本滚动;给滚动文本添加独立的溢出隐藏容器,确保滚动范围覆盖屏幕宽度:
import { XMarkIcon } from '@heroicons/react/20/solid'; export default function MarqueeBanner() { return ( <div className="relative bg-[#B8A78D] py-2 px-6 sm:px-3.5 font-helveticaNeueLight"> {/* 滚动文本容器:溢出隐藏,占满父容器宽度 */} <div className="overflow-hidden"> <p className="text-sm leading-6 text-white animate-marquee whitespace-nowrap"> <a href="#"><span className="font-bold">Just In:</span> We’re closed for holidays from December 20th 2021 to Jan 9th 2022</a> </p> </div> {/* 关闭按钮:绝对定位在右上角 */} <button type="button" className="absolute right-3 top-1/2 transform -translate-y-1/2 -m-3 p-3 focus-visible:outline-offset-[-4px]"> <span className="sr-only">Dismiss</span> <XMarkIcon className="h-5 w-5 text-white" aria-hidden="true" /> </button> </div> ); }
2. 更新Tailwind动画配置
调整关键帧,让文本从屏幕右侧进入、向左滚动至完全离开屏幕;同时增加动画时长,让滚动更自然:
/** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./src/pages/**/*.{js,ts,jsx,tsx}", "./src/components/**/*.{js,ts,jsx,tsx}", './next.config.js', ], theme: { extend: { fontFamily: { blairItcMedium: 'Blair ITC Medium, sans-serif', helveticaNeueLight: 'Helvetica Neue Light, sans-serif', }, animation: { // 调整时长为15秒,线性匀速滚动 marquee: 'marquee 15s linear infinite', }, keyframes: { marquee: { // 起始位置:文本完全在屏幕右侧 '0%': { transform: 'translateX(100%)' }, // 结束位置:文本完全离开屏幕左侧 '100%': { transform: 'translateX(-100%)' }, }, }, } }, plugins: [require('@tailwindcss/typography'), require('@tailwindcss/forms')], }
3. 可选:实现无缝滚动(重复文本)
如果希望滚动无空白间隙,可以复制文本内容,让滚动容器宽度足够覆盖屏幕:
// 修改滚动文本部分 <div className="overflow-hidden"> <div className="flex animate-marquee"> <p className="text-sm leading-6 text-white whitespace-nowrap pr-8"> <a href="#"><span className="font-bold">Just In:</span> We’re closed for holidays from December 20th 2021 to Jan 9th 2022</a> </p> {/* 重复文本实现无缝 */} <p className="text-sm leading-6 text-white whitespace-nowrap"> <a href="#"><span className="font-bold">Just In:</span> We’re closed for holidays from December 20th 2021 to Jan 9th 2022</a> </p> </div> </div>
同时调整keyframes为:
keyframes: { marquee: { '0%': { transform: 'translateX(0%)' }, '100%': { transform: 'translateX(-50%)' }, }, },
这样两个文本会连续滚动,不会出现空白。
效果说明
- 关闭按钮固定在右上角,不随文本滚动
- 文本从屏幕右侧平滑向左滚动,直至完全离开屏幕后循环
- 可选的无缝滚动方案适合短文本场景,避免滚动间隙
内容的提问来源于stack exchange,提问作者methuselah
相关产品推荐
相关产品推荐

