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


当前回答

找到了一个变通的解决方案。假设你想滚动到一个div,比如这里的Element,你想在它上面有一个20px的间距。 在上面设置一个已创建的div的ref:

<div ref={yourRef} style={{position: 'relative', bottom: 20}}/> < / >元素

这样做将创建您想要的间距。

如果你有一个标题,在标题后面创建一个空的div,并给它分配一个与标题高度相等的高度并引用它。

其他回答

基于之前的答案,我在一个Angular5项目中这样做。

开始:

// el.scrollIntoView(true);
el.scrollIntoView({
   behavior: 'smooth',
   block: 'start'
});
window.scrollBy(0, -10); 

但这样会产生一些问题,需要为scrollBy()设置timeout,如下所示:

//window.scrollBy(0,-10);
setTimeout(() => {
  window.scrollBy(0,-10)
  }, 500);

它在MSIE11和Chrome 68+中工作完美。我没有在FF测试过。500毫秒是我敢说的最短延迟。向下走有时会失败,因为平滑的滚动还没有完成。根据您自己的项目进行调整。

+1到Fred727为这个简单而有效的解决方案。

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

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();
};

2022纯js,平滑滚动,也适用于重新加载的内容

这是我对现代浏览器的解决方案:

document.addEventListener("click", e => {
   let anchorlink = e.target.closest('a[href^="#"]');
   
   if (anchorlink) {
      e.preventDefault();
      let hashval = anchorlink.getAttribute('href')
      let target = document.querySelector(hashval)
      const yOffset = -75;
      const y = target.getBoundingClientRect().top + window.pageYOffset + yOffset;
      window.scrollTo({ top: y, behavior: 'smooth' });
 
      history.pushState(null, null, hashval)
      e.preventDefault();
   }
})

click-eventlistener监听文档,因此您不必担心运行时加载或创建的实习链接(例如在wordpress中使用gutenberg)

希望能有所帮助;)

找到了一个变通的解决方案。假设你想滚动到一个div,比如这里的Element,你想在它上面有一个20px的间距。 在上面设置一个已创建的div的ref:

<div ref={yourRef} style={{position: 'relative', bottom: 20}}/> < / >元素

这样做将创建您想要的间距。

如果你有一个标题,在标题后面创建一个空的div,并给它分配一个与标题高度相等的高度并引用它。

对于表行中的元素,使用JQuery获取所需元素的上方行,然后简单地滚动到该行。

假设我在一个表中有多行,其中一些行应该由和admin检查。需要审查的每一行都有向上和向下的箭头,引导您到上一项或下一项进行审查。

这是一个完整的例子,如果你在记事本中创建一个新的HTML文档并保存它,它应该会运行。还有额外的代码来检测项目的顶部和底部以进行检查,这样我们就不会抛出任何错误。

<html>
<head>
    <title>Scrolling Into View</title>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <style>
        div.scroll { height: 6em; width: 20em; overflow: auto; }
        thead th   { position: sticky; top: -1px; background: #fff; }
        .up, .down { cursor: pointer; }
        .up:hover, .down:hover { color: blue; text-decoration:underline; }
    </style>
</head>
<body>
<div class='scroll'>
<table border='1'>
    <thead>
        <tr>
            <th>Review</th>
            <th>Data</th>
        </tr>
    </thead>
    <tbody>
        <tr id='row_1'>
            <th></th>
            <td>Row 1 (OK)</td>
        </tr>
        <tr id='row_2'>
            <th></th>
            <td>Row 2 (OK)</td>
        </tr>
        <tr id='row_3'>
            <th id='jump_1'><span class='up'>UP</span> <span class='down'>DN</span></th>
            <td>Row 3 (REVIEW)</td>
        </tr>
        <tr id='row_4'>
            <th></th>
            <td>Row 4 (OK)</td>
        </tr>
        <tr id='row_5'>
            <th id='jump_2'><span class='up'>UP</span> <span class='down'>DN</span></th>
            <td>Row 5 (REVIEW)</td>
        </tr>
        <tr id='row_6'>
            <th></th>
            <td>Row 6 (OK)</td>
        </tr>
        <tr id='row_7'>
            <th></th>
            <td>Row 7 (OK)</td>
        </tr>
        <tr id='row_8'>
            <th id='jump_3'><span class='up'>UP</span> <span class='down'>DN</span></th>
            <td>Row 8 (REVIEW)</td>
        </tr>
        <tr id='row_9'>
            <th></th>
            <td>Row 9 (OK)</td>
        </tr>
        <tr id='row_10'>
            <th></th>
            <td>Row 10 (OK)</td>
        </tr>
    </tbody>
</table>
</div>
<script>
$(document).ready( function() {
    $('.up').on('click', function() {
        var id = parseInt($(this).parent().attr('id').split('_')[1]);
        if (id>1) {
            var row_id = $('#jump_' + (id - 1)).parent().attr('id').split('_')[1];
            document.getElementById('row_' + (row_id-1)).scrollIntoView({behavior: 'smooth', block: 'start'});
        } else {
            alert('At first');
        }
    });

    $('.down').on('click', function() {
        var id = parseInt($(this).parent().attr('id').split('_')[1]);
        if ($('#jump_' + (id + 1)).length) {
            var row_id = $('#jump_' + (id + 1)).parent().attr('id').split('_')[1];
            document.getElementById('row_' + (row_id-1)).scrollIntoView({behavior: 'smooth', block: 'start'});
        } else {
            alert('At last');
        }
    });
});
</script>
</body>
</html>