如何增强D3.js'平滑滚动'演示?

时间:2015-11-07 10:13:30

标签: javascript d3.js transition tween

js people,

我正在看这个演示:

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

它显示了一个平滑的滚动'滚动到页面末尾的技术。

如何增强它以便滚动到id或选择?

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

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

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

2 个答案:

答案 0 :(得分:0)

而不是一直到最后,你可以计算偏移为

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/

答案 1 :(得分:0)

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

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