我有一个页面,其中一个滚动条包含从数据库动态生成的带有div的表行。每个表行就像一个链接,有点像你在视频播放器旁边看到的YouTube播放列表。

当用户访问页面时,他们所在的选项应该会转到滚动div的顶部。这个功能正在工作。问题是,这有点太过分了。比如他们的选项高了10像素。因此,页面被访问,url被用来识别选择了哪个选项,然后将该选项滚动到滚动div的顶部。注意:这不是窗口的滚动条,这是一个带有滚动条的div。

我正在使用这段代码,使它移动选中的选项到div的顶部:

var pathArray = window.location.pathname.split( '/' );

var el = document.getElementById(pathArray[5]);

el.scrollIntoView(true);

它将它移动到div的顶部,但大约10个像素太高了。 有人知道怎么解决吗?


当前回答

你也可以使用element.scrollIntoView()选项

el.scrollIntoView(
  { 
    behavior: 'smooth', 
    block: 'start' 
  },
);

大多数浏览器都支持

其他回答

CSS滚动边距和滚动填充

你可能想看看新的CSS属性滚动填充和滚动边距。可以对滚动容器(在本例中为html)使用滚动填充,对容器内的元素使用滚动边距。

在你的例子中,你想为你想要滚动到视图中的元素添加scroll-margin-top,如下所示:

.example {
  scroll-margin-top: 10px;
}

这会影响scrollIntoView代码,如下所示:

const el = document.querySelector(".example");
el.scrollIntoView({block: "start", behavior: "smooth"});

这将导致视口滚动以使视口的上边界与元素的上边界对齐,但有10px的额外空间。换句话说,元素的这些属性被考虑在内:

padding-top border-top scroll-margin-top (而不是margin-top)

此外,如果html元素有滚动填充顶部设置,那么也会考虑这一点。

另一个解决方案是使用"offsetTop",就像这样:

var elementPosition = document.getElementById('id').offsetTop;

window.scrollTo({
  top: elementPosition - 10, //add your necessary value
  behavior: "smooth"  //Smooth transition to roll
});

这适用于我的Chrome浏览器(平滑滚动,没有计时黑客)

它只是移动元素,开始滚动,然后再移动回来。

如果元素已经在屏幕上,则不会出现可见的“弹出”。

pos = targetEle.style.position;
top = targetEle.style.top;
targetEle.style.position = 'relative';
targetEle.style.top = '-20px';
targetEle.scrollIntoView({behavior: 'smooth', block: 'start'});
targetEle.style.top = top;
targetEle.style.position = pos;

平滑滚动到适当的位置

这是大多数情况下更好的答案。它使用滚动边距和滚动填充CSS规则。 下面的解决方案使用getBoundingClientRect,它会触发一个额外的强制布局。

得到正确的y坐标并使用window。scrollTo({top: y,行为:'平滑'})

const id = 'profilePhoto';
const yOffset = -10; 
const element = document.getElementById(id);
const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;

window.scrollTo({top: y, behavior: 'smooth'});

根据arsenie - ii的回答:我有一个用例,其中滚动实体不是窗口本身,而是一个内部模板(在这种情况下是div)。在这个场景中,我们需要为滚动容器设置一个ID,并通过getElementById获取它来使用它的滚动函数:

<div class="scroll-container" id="app-content">
  ...
</div>
const yOffsetForScroll = -100
const y = document.getElementById(this.idToScroll).getBoundingClientRect().top;
const main = document.getElementById('app-content');
main.scrollTo({
    top: y + main.scrollTop + yOffsetForScroll,
    behavior: 'smooth'
  });

把它留在这里,以防有人面临类似的情况!