水平滚动到视图中心

17
我需要让最后一步进入视图,但不要丢失标题(因为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>

);};

您可以查看一个代码沙箱


欢迎来到 Stack Overflow。请将您的代码贴在问题中,而不是外部链接中。 - StudioTime
我不确定你想说什么。据我理解,你想要避免垂直滚动条。请在你的 index.css 文件中添加 body{ overflow-y: hidden}。 - Farhan Ali
Element.scrollIntoViewIfNeeded()也可能很有用。https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded - Esger
1个回答

27

看起来你已经在代码沙盒中完成了这个操作,但是添加属性 block: 'nearest' 可以在大多数情况下解决这个问题。scrollIntoView 仍会尝试将元素垂直滚动到视图中,但不会尝试垂直居中。

activeStep.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' })

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView


4
这很有帮助,但我认为没有回答问题:“如何只水平滚动,而不是垂直滚动”。 - Josh Noe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接