简体   繁体   English

为什么 Chrome 会自动滚动以包含被点击的元素?

[英]Why does Chrome auto-scroll to contain the clicked element?

Recently I noticed that while performing ajax page updates (appends to a block, to be specific, like in "Show more comments" scenarios) Chrome started performing some kind of automatic scroll in order to keep the clicked element in view, it seems.最近我注意到,在执行 ajax 页面更新时(附加到一个块,具体来说,就像在“显示更多评论”场景中)Chrome 开始执行某种自动滚动以保持被点击的元素在视图中,看起来。

What is this?这是什么? Why has it been introduced and how to get rid of this behaviour?为什么要引入它以及如何摆脱这种行为?

Minimum(ish) reproducible code here:此处的最小(ish)可重现代码:

 $(document).ready(function() { var html = $(".container").html(); $("#load-more").click(function(){ $(".container").append(html); }) })
 .container { width: 400px; margin: 0 auto; background-color: aqua; padding: 1em; }
 <:DOCTYPE html> <html> <head> <script src="https.//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div class="container"> <article> <h3>Foo Bar 1</h3> <p>hello world</p> </article> <article> <h3>Foo Bar 2</h3> <p>hello world</p> </article> <article> <h3>Foo Bar 3</h3> <p>hello world</p> </article> </div> <button id="load-more">load more</button> </body> </html>

Note how in Chrome(ium) the clicked button stays in view, contrary to what one would expect.请注意在 Chrome(ium) 中单击的按钮如何保持在视图中,这与人们所期望的相反。

This is called Scroll Anchoring and has been a feature/flag in Chromium for quite a few years now.这被称为滚动锚定,并且多年来一直是 Chromium 中的一个功能/标志。

Luckily, it can be disabled through css.幸运的是,它可以通过 css 禁用。

body {
    overflow-anchor: none;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-anchor/Guide_to_scroll_anchoring https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-anchor/Guide_to_scroll_anchoring

As a user of the web, you are probably familiar with the problem that scroll anchoring solves.作为 web 的用户,您可能对滚动锚定解决的问题很熟悉。 You browse to a long page on a slow connection and begin to scroll to read the content;您在慢速连接上浏览到长页面并开始滚动阅读内容; while you are busy reading, the part of the page you are looking at suddenly jumps.当您忙于阅读时,您正在查看的页面部分突然跳跃。 This has happened because large images or some other elements have just loaded further up in the content.发生这种情况是因为大图像或其他一些元素刚刚在内容中加载得更远。

Scroll anchoring is a browser feature that aims to solve this problem of content jumping, which happens if content loads in after the user has already scrolled to a new part of the document.滚动锚定是一种浏览器功能,旨在解决内容跳转问题,如果内容在用户已经滚动到文档的新部分后加载,就会发生这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM