【问题标题】:How to enhance D3.js 'smooth scrolling' demo?如何增强 D3.js 的“平滑滚动”演示?
【发布时间】:2015-11-07 10:13:30
【问题描述】:

js 人,

我正在看这个演示:

http://bl.ocks.org/mbostock/1649463

它显示了滚动到页面末尾的“平滑滚动”技术。

如何增强它使其滚动到一个 id 或选择?

我想创建一个名为 slowscroll() 的函数。

我希望 API 调用看起来像这样:

d3.select('#mybutton')
  .on('click',function(){
    slowscroll(mydelay, myduration, '#stophere');});

【问题讨论】:

    标签: javascript d3.js transition tween


    【解决方案1】:

    你可以做这样的事情来停止点击按钮并从那里恢复。

    //add listener to stop
    d3.select("#stop").on("click", function () {
        //stop the transition
        d3.select("body").transition().duration(0);
    });
    //add listeners to resume
    d3.select("#resume").on("click", function () {
        //resume the transition
        d3.select("body").transition()
        .delay(1)
        .duration(7500)
        .tween("scroll", scrollTween(document.body.getBoundingClientRect().height - window.innerHeight));
    });
    

    完整的工作代码here

    【讨论】:

      【解决方案2】:

      您可以将偏移量计算为

      ,而不是一直走到最后
      var offset = $(selector).offset().top - window.scrollY;
      

      然后在函数中使用它

      function scrollToElem(delay, duration, selector){
      var offset = $(selector).offset().top - window.scrollY;
      
      d3.transition()
          .delay(1500)
          .duration(7500)
          .tween("scroll", scrollTween(offset));
      
      }
      

      事件绑定

      d3.select('#my-button')
      .on('click',function(){
      scrollToElem(1500, 7500, '#target');});
      

      这里是完整的代码 https://jsfiddle.net/mddm8xxt/2/

      【讨论】:

      • 这实际上不是一个通用的解决方案,看看jsfiddle.net/mddm8xxt/3 在点击按钮之前滚动一下会发生什么
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      相关资源
      最近更新 更多