我有一个页面,其中一个滚动条包含从数据库动态生成的带有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个像素太高了。 有人知道怎么解决吗?


当前回答

假设你想滚动到DOM中相同级别的div,并且类名为“scroll-with-offset”,那么这个CSS将解决这个问题:

.scroll-with-offset {    
  padding-top: 100px;
  margin-bottom: -100px;
}

与页面顶部的偏移量为100px。它只会像block: 'start'那样工作:

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

所发生的事情是div的顶部在正常位置,但它们的内部内容开始低于正常位置100px。这就是padding-top:100px的作用。margin-bottom: -100px用来抵消下面div的额外边距。 为了使解决方案完整,还添加了这个CSS来抵消最顶部和最底部div的边距/填充:

.top-div {
  padding-top: 0;
}
.bottom-div {
  margin-bottom: 0;
}

其他回答

也许这有点笨拙,但到目前为止还不错。我在angular 9工作。

文件.ts

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

. html文件

<button (click)="scroll(target)"></button>
<div  #target style="margin-top:-50px;padding-top: 50px;" ></div>

我用边距和填充顶部调整偏移量。

问候!

我用,

element.scrollIntoView({ behavior: 'smooth', block: 'center' });

这使得元素在滚动后出现在中心,所以我不需要计算yOffset。

希望能有所帮助……

我添加这些css技巧给那些没有解决这个问题的解决方案:

#myDiv::before {
  display: block;
  content: " ";
  margin-top: -90px; // adjust this with your header height
  height: 90px; // adjust this with your header height
  visibility: hidden;
}

你可以分两步完成:

el.scrollIntoView(true);
window.scrollBy(0, -10); // Adjust scrolling with a negative value here

根据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'
  });

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