如何增强 D3.js 'smooth scrolling' 演示?

How to enhance D3.js 'smooth scrolling' demo?

js人,

我正在看这个演示:

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

它展示了滚动到页面末尾的 'smooth scrolling' 技术。

如何增强它以使其滚动到某个 ID 或选择?

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

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

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

您可以将偏移量计算为

,而不是一路走到尽头
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/

您可以像这样在单击按钮时停止并从那里继续。

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