Stop automatic scrolling on page content change

2020-08-19 07:02发布

问题:

I have a page which adds and removes some content to itself on a scroll event.

Now when using Chrome(IE11 doesn't seem to have this behaviour), whenever the content is added and removed to the page a scroll event is generated (I guess in order to keep the client view consistent on page changes).

I don't want this. The scroll event generated on the content change will trigger more content changes which will in turn trigger more scroll events.

Any advice on how I can stop this behaviour for all browsers? I don't want any automatic scrolling to happen. I only want user scrolling to be registered.

Here is some simple example code. Clicking the "click" button will reshuffle the colored diffs and make the page scroll by itself (in Chrome, not IE11)...

function removeStuff(){
    var elem = document.getElementById("center");
    document.getElementById("container").removeChild(elem);
    document.getElementById("container").appendChild(elem);
}
#top {
    background-color: green;
    height:1500px;

}

#center {
    background-color: blue;
    height:1000px;
}

#bottom {
    background-color: red;
    height:1500px;
}
<div id="container">
  <div id="top"></div>
  <div id="center"></div>
  <button id="button" onclick="removeStuff()">click</button>
  <div id="bottom"></div>
</div>

   

回答1:

This is a Chromium feature recently added, called scroll-anchoring.

Disable in the browser: go to chrome://flags/#enable-scroll-anchoring and set "Scroll anchoring" to "Disabled".

Disable via CSS:

.some-element {
    overflow-anchor: none;
}


回答2:

I don't think you can disable this behavior, but you can work around it. Because Chrome does the scroll event synchronously when you call removeChild, you can detect these types of scroll events by setting a global boolean to true just before the removeChild and setting it back to false directly after.

var isRemovingStuff = false;
function removeStuff(){
    var elem = document.getElementById("center");

    // Chrome does a scroll here, set isRemovingStuff to true
    // so our scroll handler can know to ignore it.
    isRemovingStuff = true;
    document.getElementById("container").removeChild(elem);
    isRemovingStuff = false;

    document.getElementById("container").appendChild(elem);

   // TODO: set the scrollTop back to what you want it to be.
}

And your scroll handler would look like:

function onScroll() {
    if (isRemovingStuff)
        return;

    // Do cool stuff
}