【问题标题】:how to use d3 to scroll whole page如何使用 d3 滚动整个页面
【发布时间】:2016-12-05 03:27:29
【问题描述】:

我希望我的 d3 能够在平移时滚动整个页面。

有点像effect on challonge,但只在y轴上。

这是我的尝试。

pan.call(d3.drag().on("drag", function dragged() {
        // x axis
        thisPosX += d3.event.dx;
        g.attr("transform", "translate(" + thisPosX + ", 0)");
        g1.attr("transform", "translate(" + thisPosX + ", 0)");
        position.x = thisPosX;
        // y axis.
        var tmp = d3.event.dy;
        if (tmp != -lastTmp) {
            $window.scrollTo(0, $window.scrollY - tmp);
            lastTmp = tmp;
        }
}));

但是这段代码仍然使平移非常缓慢并且有一些尖峰。

有没有更好的方法呢?顺便说一句,我正在使用 angular。

【问题讨论】:

    标签: javascript angularjs d3.js


    【解决方案1】:

    我认为你想要做的不需要 d3。当然,您可以使用 d3 绑定事件,但拖动行为旨在拖动容器内的元素,例如 canvas 或 svg,这是静态的。

    我发现这个Codepen 可能会起作用。

    首先,我建议您将 svg 包装在一个具有拖动行为的 div 中,如果您查看其源代码,Challonge 会这样做:

    然后定义滚动拖动行为,我已经将之前的 codepen 改编为使用 d3:

    var curYPos = 0;
    var curDown = false;
    
    var scrollable = d3.select('#scrollable');
    scrollable.on('mousemove', function () {
      // Scroll only if mouse is down
      if (curDown === true){
        // Scroll only along Y
        // d3.mouse(this) is the position of the cursor inside your scrollable (this)
        window.scrollTo(0, document.body.scrollTop + (curYPos - d3.mouse(this)[1]));
      }
    });
    
    scrollable.on('mousedown', function () {
      curDown = true;
      curYPos = d3.mouse(this)[1];
    });
    scrollable.on('mouseup mouseleave', function () {
      curDown = false;
    });
    

    Demo

    【讨论】:

    • 这段代码有个bug,如果你的鼠标离开拖动区域,页面会滚动到顶部。
    • 我觉得调试没那么难!
    • 是的,我调试了它,结合 d3.mouse 和 d3.drag.on 解决了这个问题,谢谢。
    猜你喜欢
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    相关资源
    最近更新 更多