【问题标题】:scroll to follow as elements are dynamically added动态添加元素时滚动以跟随
【发布时间】:2020-02-26 20:27:35
【问题描述】:

(仅供参考,这是一个艺术项目,所以在网站上做这件事听起来不太合理)

我有一个通过 dom 向下传递的 jquery 代码,并向页面上的随机元素添加一个属性('bar')。我希望新元素在添加时滚动到视图中。我尝试了一些东西,最近使用 :eq() 来识别页面上最后一个这样的元素,但没有骰子。

        var last = $('[bar]').length;
        $('html,body').animate({scrollTop: $('[bar]:eq('+last+')').offset().top }, 100);

【问题讨论】:

    标签: javascript jquery scroll jquery-animate


    【解决方案1】:

    尝试添加一个最小的可重现示例:https://stackoverflow.com/help/minimal-reproducible-example

    这是我对你正在尝试做的事情的猜测:

    var bar_ids = ['one', 'two', 'three'];
    
    var myInterval;
    var myIndex = 0;
    var myLoopCount = 0;
    
    
    myInterval = setInterval(()=>{
      if (myLoopCount == 0){
        var att = document.createAttribute("bar"); 
        document.querySelector('#'+bar_ids[myIndex]).setAttributeNode(att);
      }  
      bars = $('[bar]');
      //console.log(bars[myIndex])
      $('html,body').animate({scrollTop: $(bars[myIndex]).offset().top }, 1000);
      myIndex +=1;
      if (myIndex >= bar_ids.length){
        myLoopCount += 1;
        myIndex = 0;
        if (myLoopCount > 5){
          clearInterval(myInterval)
        }    
      }
    },500)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="one" style="height:1200px; background:#ff0000"></div>
    <div id="two" style="height:1200px; background:#0004ff"></div>
    <div id="three" style="height:1200px; background:#00ff04"></div>

    再给我一些源代码和描述,我可能会提供更多帮助。

    最好的办法是你分叉这个 codePen:https://codepen.io/Alexander9111/pen/qBdrQLG,然后也分享它:)

    简而言之,(假设我猜你的用例足够接近/很好)你应该使用这样的选择器:

    $(bars[myIndex]).offset().top

    您可以像这样得到条形图(DOM 元素数组):

    var bars = $('[bar]');

    你可以像这样得到 myIndex:

    var myIndex = bars.length - 1;(记住数组是零索引的)

    【讨论】:

    • 谢谢!整个问题是通过从 var last 中减去 1 来解决的,忘记了零索引!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多