平滑滚动不适用于过渡动画

问题描述 投票:0回答:1

我正在将 NextJS 用于个人网站。我试图同时拥有平滑滚动和变换动画,以增加所选项目的大小。这里有一个简单的演示,展示了我想要实现的目标:

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function ScrollContainer() {
  const [selectedIndex, setSelectedIndex] = React.useState(0)
  const itemRefs = React.useRef([])

  React.useEffect(() => {
    itemRefs.current = itemRefs.current.slice(0, items.length)
  }, [])

  const handleItemClick = (index) => {
    if (index !== selectedIndex) {
      setSelectedIndex(index)
      itemRefs.current[index].scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'center'
      })
    }
  }

  return (
    <div className="w-full h-screen flex items-center justify-center bg-gray-100">
      <div className="w-full max-w-3xl overflow-hidden">
        <div className="flex space-x-4 px-4 py-8 overflow-x-auto snap-x snap-mandatory scrollbar-hide">
          {items.map((item, index) => (
            <div
              key={item}
              ref={el => itemRefs.current[index] = el}
              className={`flex-shrink-0 w-32 h-32 flex items-center justify-center text-2xl font-bold text-white rounded-lg snap-center transition-all duration-300 ease-in-out cursor-pointer
                ${index === selectedIndex ? 'bg-blue-500 scale-110' : 'bg-gray-400 scale-100 hover:bg-gray-500'}`}
              onClick={() => handleItemClick(index)}
            >
              {item}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

ReactDOM.createRoot(
  document.getElementById("root")
).render(
  <ScrollContainer />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

编辑:平滑滚动在 Firefox 中工作正常,但在 Chrome 中则不然 🙁

javascript reactjs scroll
1个回答
0
投票

您是否尝试过使用 Tailwind 实现滚动平滑并且您使用的是最新版本?试试这个代码:

<div className="flex space-x-4 px-4 py-8 overflow-x-auto snap-x snap-mandatory scrollbar-hide scroll-smooth">

© www.soinside.com 2019 - 2024. All rights reserved.