我需要最后一步进入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>
); };
你可以看到一个代码沙箱
看起来您已经在代码沙箱中完成了此操作,但添加 block: 'nearest' 属性应该在大多数情况下解决此问题。 scrollIntoView 仍会尝试将元素垂直置于视图中,但不会尝试将其垂直居中。
activeStep.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' })
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
const scrollIntoViewHorizontally = (
container,
child,
) => {
const child_offsetRight = child.offsetLeft + child.offsetWidth;
const container_scrollRight = container.scrollLeft + container.offsetWidth;
if (container.scrollLeft > child.offsetLeft) {
container.scrollLeft = child.offsetLeft;
} else if (container_scrollRight < child_offsetRight) {
container.scrollLeft += child_offsetRight - container_scrollRight;
}
};
const scrollIntoViewHorizontally = (
container,
child,
) => {
const childOffsetRight = child.offsetLeft + child.offsetWidth;
const containerScrollRight = container.scrollLeft + container.offsetWidth;
if (container.scrollLeft > child.offsetLeft) {
container.scrollLeft = child.offsetLeft;
} else if (containerScrollRight < childOffsetRight) {
container.scrollLeft += childOffsetRight - containerScrollRight;
}
};
const container = document.querySelector('.container');
const tabs = document.querySelectorAll('.tabs');
document.addEventListener('click', (e) => {
if(e.target.classList.contains('tab')) {
scrollIntoViewHorizontally(container, e.target);
}
});
.container {
display: flex;
overflow: auto;
width: 200px;
height: 48px;
border: 1px solid black;
}
.tab {
display: flex;
padding: 6px 12px;
flex-shrink: 0;
height: 100%;
align-items: center;
cursor: pointer;
border: none;
background: transparent;
}
.tab:hover, .tab:focus {
background: #eee;
}
<div class="container">
<button class="tab">tab 1</button>
<button class="tab">tab 2</button>
<button class="tab">tab 3</button>
<button class="tab">tab 4</button>
<button class="tab">tab 5</button>
<button class="tab">tab 6</button>
<button class="tab">tab 7</button>
<button class="tab">tab 8</button>
</div>