简体   繁体   中英

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.

What is this? Why has it been introduced and how to get rid of this behaviour?

Minimum(ish) reproducible code here:

 $(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.

This is called Scroll Anchoring and has been a feature/flag in Chromium for quite a few years now.

Luckily, it can be disabled through css.

body {
    overflow-anchor: none;
}

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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