仅水平滚动到视图中

Ser*_*sca 22 javascript reactjs

我需要最后一步进入View,但不能丢失标题,(因为scrollIntoView也垂直滚动)

如何实现它仅水平滚动而不垂直滚动到视图中

const App = () => {
  React.useEffect(() => {
  const activeStep = document.querySelector(".ant-steps-item- 
  current");

  if (activeStep) {
    activeStep.scrollIntoView({ behavior: "smooth", inline: 
  "center" });
   }
    }, []);

  return (
   <div style={{ minHeight: "200vh" }}>
    <div style={{ height: "150px", fontSize: 
    "5rem"}}>Title</div>
  <Steps>
    {steps.map((s, step) => {
      const status = s === "step9" ? "current" : "";
      return (
        <Steps.Step status={status} key={step} title={s} 
    description={s} />
       );
       })}
   </Steps>
  </div>
Run Code Online (Sandbox Code Playgroud)

);};

你可以看到一个代码沙箱

Ste*_*ers 30

看起来您已经在代码沙箱中完成了此操作,但添加 block: 'nearest' 属性应该在大多数情况下解决此问题。scrollIntoView 仍会尝试将元素垂直置于视图中,但不会尝试将其垂直居中。

activeStep.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' })
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

  • 这很有帮助,但 IMO 没有回答这个问题:“如何仅水平滚动到视图,而不是垂直滚动到视图” (5认同)