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


当前回答

20秒内搞定:

这个解属于@ arsenie - ii,我只是把它简化成一个函数。

function _scrollTo(selector, yOffset = 0){
  const el = document.querySelector(selector);
  const y = el.getBoundingClientRect().top + window.pageYOffset + yOffset;

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

使用方法(您可以在StackOverflow中打开控制台并进行测试):

_scrollTo('#question-header', 0);

我目前正在生产中使用它,它工作得很好。

其他回答

我添加这些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;
}

把我的解决方案留在这里,以防有人想达到和我一样的目标。

在我的例子中,错误或通知出现在提交后的页面顶部。(游戏邦注:对于几页滚动来说,页面有点长,在手机上则更长。)

我使用下面的代码片段将错误或通知滚动到视图中。

requestAnimationFrame (() = > errorOrNotification.scrollIntoView ({ Block: 'end', behavior: 'smooth' }) );

Block: 'end'是窍门。根据文档::它反映了alignToTop: false场景。为了融合平滑滚动,我添加了相同的替换。

从本质上讲,它将尝试将元素的底部与可滚动祖先(在我的例子中是窗口)的可见区域的底部对齐。

一种解决方案是创建一个相对于目标具有偏移量的不可见临时元素,滚动到它,然后删除它。这也许不是最理想的,但在我工作的环境中,其他解决方案对我不起作用。例如:

const createOffsetElement = (element) => {
    const offsetElement = document.createElement('div');
    offsetElement.style = `
        position: relative;
        top: -10em;
        height: 1px;
        width: 1px;
        visibility: hidden;
    `;
    const inputWrapper = element.closest('.ancestor-element-class');
    inputWrapper.appendChild(offsetElement);
    return offsetElement;
};

const scrollTo = (element) => {
    const offsetElement = createOffsetElement(element);
    offsetElement.scrollIntoView({
        behavior: 'smooth',
    });
    offsetElement.remove();
};

你可以分两步完成:

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

20秒内搞定:

这个解属于@ arsenie - ii,我只是把它简化成一个函数。

function _scrollTo(selector, yOffset = 0){
  const el = document.querySelector(selector);
  const y = el.getBoundingClientRect().top + window.pageYOffset + yOffset;

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

使用方法(您可以在StackOverflow中打开控制台并进行测试):

_scrollTo('#question-header', 0);

我目前正在生产中使用它,它工作得很好。