Issue where adding new elements to the top of container pushes the viewport down (scrolls the page down)

huangapple go评论66阅读模式
英文:

Issue where adding new elements to the top of container pushes the viewport down (scrolls the page down)

问题

I have this code where I have a container that I'm dynamically adding new elements to the top of the container (Like news coming in from the top). The issue is that when the viewport is scrolled down slightly it is pushed down each time a new element is added - And I would really like for that not to happen.

这段代码中,我有一个容器,我在容器顶部动态添加新元素(类似新闻从顶部进来)。问题是,当视口稍微向下滚动时,每次添加新元素时,它都会被推下来 - 我真的不希望这种情况发生。

Here is a very simplified version of the code:

这是代码的一个非常简化的版本:

HTML

HTML

<div class="container">
   <div id="newelementwrapper">
   </div>
</div>

CSS

CSS

body {
      min-height: 2000px;
    }
    .container {
      height: 500px;
      width: 100%;
      overflow: hidden;
      background-color: green;
    }
    
    #newelementwrapper {
      height: 100%;
      overflow-y: scroll;
    }
    
    .element {
      height: 100px;
      background-color: red;
      width: 400px;
      margin: 20px;
    }

JS:

JS:

// Returns a Promise that resolves after "ms" Milliseconds
    const bubblesContainer = document.getElementById("newelementwrapper")
    
    const timer = ms => new Promise(res => setTimeout(res, ms))

    //Creates and adds the bubbles from data and calls map functions with delay specified by the timer
    async function addBubbles () {
        for (let i = 0; i < 100; i++) {
            //Create bubble
            const bubble = '<div class="element">Element</div>';
            //Insert bubble
            bubblesContainer.insertAdjacentHTML('afterbegin', bubble);
            //Delay
            await timer(1500);
        }
    }
    
    addBubbles()

Here is a fiddle with the same example:
https://jsfiddle.net/cpzbmh79/2/

You need to scroll down a bit for the issue to appear.

这里有一个使用相同示例的fiddle链接:
https://jsfiddle.net/cpzbmh79/2/

您需要稍微向下滚动一点才能看到这个问题。

英文:

I have this code where I have a container that I'm dynamically adding new elements to the top of the container (Like news comming in from the top).
The issue is that when the viewport is scrolled down slightly it is pushed down each time e new element is added - And i would really like for that not to happen.

Here is a very simplified version of the code:

HTML

&lt;div class=&quot;container&quot;&gt;
   &lt;div id=&quot;newelementwrapper&quot;&gt;
   &lt;/div&gt;
&lt;/div&gt;

CSS

body{
      min-height:2000px;
    }
    .container {
      height: 500px;
      width: 100%;
      overflow: hidden;
      background-color: green;
    }
    
    #newelementwrapper {
      height: 100%;
      overflow-y: scroll;
    }
    
    .element {
      height: 100px;
      background-color: red;
      width: 400px;
      margin: 20px;
    }

JS:

// Returns a Promise that resolves after &quot;ms&quot; Milliseconds
    const bubblesContainer = document.getElementById(&quot;newelementwrapper&quot;)
    
    const timer = ms =&gt; new Promise(res =&gt; setTimeout(res, ms))

    //Creates and ads the bubbles from data and calls map functions width dealy specified by the timer
    async function addBubbles () {
        for (let i = 0; i &lt; 100; i++) {
            //Create bubble
            const bubble = &#39;&lt;div class=&quot;element&quot;&gt;Element&lt;/div&gt;&#39;
            //Insert bubble
            bubblesContainer.insertAdjacentHTML(&#39;afterbegin&#39;,bubble);
            //Delay
            await timer(1500);
        }
    }
    
    addBubbles()

Here is a fiddle with the same example:
https://jsfiddle.net/cpzbmh79/2/

You need to scroll down a bit for the issue to appear.

答案1

得分: 1

你可以尝试手动设置滚动位置。这很棘手,但你需要获取元素的现有垂直滚动位置以及窗口的现有垂直滚动位置。

根据你的示例,我调整了addBubbles函数以使其正常工作:

    async function addBubbles() {
        let newelementwrapper = document.getElementById('newelementwrapper')

        for (let i = 0; i < 100; i++) {
            // 获取当前滚动位置
            let windowPosition = window.scrollY,
                elementPosition = newelementwrapper.scrollTop;

            // 创建气泡
            const bubble = '<div class="element">Element</div>';

            // 插入气泡
            bubblesContainer.insertAdjacentHTML('afterbegin', bubble);

            // 设置滚动位置
            newelementwrapper.scrollTop = elementPosition
            window.scrollTo(0, windowPosition)

            // 延迟
            await timer(1000);
        }
    }

我注意到你的示例中,你是将新元素添加到div的底部而不是顶部,但在你的原始问题中,你指示要将div添加到元素的顶部。不确定这个解决方案是否适用于这种情况,但这是一个起点。

英文:

You could try setting the scroll position manually. It's tricky, but you would need to get the existing vertical scroll position of the element as well as the existing vertical scroll position of the window.

Based on your fiddle, I adjusted the addBubbles function to make it work

    async function addBubbles () {
        let newelementwrapper = document.getElementById(&#39;newelementwrapper&#39;)

        for (let i = 0; i &lt; 100; i++) {
            // Get current scroll position
            let windowPosition = window.scrollY,
                elementPosition = newelementwrapper.scrollTop;

            //Create bubble
            const bubble = &#39;&lt;div class=&quot;element&quot;&gt;Element&lt;/div&gt;&#39;

            //Insert bubble
            bubblesContainer.insertAdjacentHTML(&#39;afterbegin&#39;,bubble);

            // Set scroll position
            newelementwrapper.scrollTop = elementPosition
            window.scrollTo(0, windowPosition)

            //Delay
            await timer(1000);
        }
    }

One thing I noticed is that in your fiddle you are adding new elements to the bottom of the div instead of the top, but in your original question you indicated you were adding divs to the top of an element. Not sure if this solution would work with that but it's a starting point.

huangapple
  • 本文由 发表于 2023年4月17日 20:49:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035340.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定