scrollIntoView() 移动整个页面

新手上路,请多包涵

环境:Firefox 1627 和 Chrome 33

我有一个 <div> (带滚动条),其中包含很多元素 <p>

If I call scrollIntoView() on a <p> element, I expect only the scroll of the div to move, but the complete page (outside of the <div> ) 滚动。

JSFiddle 示例:http: //jsfiddle.net/7fH8K/7/

这里出了什么问题?

原文由 Bhuvan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 981
2 个回答

只需使用参数 false 调用 scrollIntoView() 以指示不应滚动到顶部。

有关详细信息,请参阅 MDN 上 Element.scrollIntoView() 的说明

JSFiddle 页面向下滚动的原因是 scrollIntoView() 滚动所有可滚动的祖先元素以显示你调用的元素 scrollIntoView() 上。并且由于页面的 <body> 实际上高于视口,但仅通过 overflow: hidden; 隐藏了滚动,它向下滚动页面试图对齐 p 元素与顶部。

这是此行为的一个简单示例:

文件 scroll.html

 <!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>Main page</title>
        <style type="text/css">
        html, body {
            height: 120%;
            width: 100%;
            overflow: hidden;
        }

        header {
            height: 100px;
            width: 100%;
            background-color: yellow;
        }

        iframe {
            height: 100px;
            width: 300px;
        }
        </style>
    </head>
    <body>
        <header></header>
        <iframe src="scroll2.html"></iframe>
    </body>
</html>

文件 scroll2.html

 <!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>Scrolling &lt;iframe&gt;</title>
        <script type="text/javascript">
        function scrollLastParagraphIntoView() {
            var lastParagraph = document.getElementById("p10");
            lastParagraph.scrollIntoView();
        }
        </script>
    </head>
    <body>
        <button onclick="scrollLastParagraphIntoView()">Scroll last paragraph into view</button>
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
        <p>Paragraph 3</p>
        <p>Paragraph 4</p>
        <p>Paragraph 5</p>
        <p>Paragraph 6</p>
        <p>Paragraph 7</p>
        <p>Paragraph 8</p>
        <p>Paragraph 9</p>
        <p id="p10">Paragraph 10</p>
    </body>
</html>

当您单击将 最后一段滚动到视图 按钮时,整个页面将滚动,以便该段落显示在视口的顶部。

原文由 Sebastian Zartner 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用:

 scrollIntoView({ block: 'end' })

或平滑滚动:

 scrollIntoView({ block: 'end', behavior: 'smooth' })

原文由 Sunil Tako 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题