【问题标题】:Easy way to slide down an SVG element?向下滑动 SVG 元素的简单方法?
【发布时间】:2012-10-12 17:22:02
【问题描述】:

对于 SVG 元素是否有与 jQuery 的 slideDown 方法等效的方法?现在这些元素只是突然出现。我想通过向下滑动来软化一点。

编辑: 我的代码基于此处的动态堆叠条形图:http://benjchristensen.com/2011/12/16/dynamic-stacked-bar-chart-using-d3-js/

我不是一个带有许多条的图表,而是有许多带有一个条的图表。我想让它当图表出现时,它会慢慢滑下来。

【问题讨论】:

    标签: javascript jquery svg d3.js


    【解决方案1】:

    我不相信 jQuery 很容易支持 SVG。 Keith Wood 有一个SVG specific jQuery library,它允许你做一些动画。

    另一种选择是使用支持 SVG 的图形库。首先想到的是D3.js,它提供了一些非常易于使用的方法来操作 SVG 元素。此外,选择器样式类似于您可能习惯于 jQuery 的样式。

    如果您使用 D3,我会查看 transition 方法。您可以做很多事情,而 D3 非常强大。一个例子是:

    var rect = d3.select('#rectangle');
    // this selects a rectangle.  Let's say that it starts at 
    // the origin, or even off screen in your case   
    
    rect.transition()
        .duration(250)
        .attr('x', 10)
        .attr('y', 20); 
        // this changes the x and y attributes
        // of the rectangle to 10 and 20 respectively
        // using a transition over a 250ms duration.
    

    对于您给出的特定示例,我只需更改 y 属性,使其从屏幕开始(例如 y = -1 * height),然后将其转换为 y = heighty = 200 或类似的东西。

    【讨论】:

    • 我实际上在使用 D3,但不确定如何为元素添加动画。让我编辑我的原始帖子。
    • 如果代码附加了一些东西,我想我应该在附加之后进行转换?还是以前?
    • @PLui 好问题。这实际上取决于您如何设置代码/数据。如果您使用某些数据源将 SVG 元素附加到 DOM,那么您应该使用 Mike Bostock 在他的文章 "Thinking with Joins" 中定义的“绑定、输入、更新、退出”模型。您首先定义要选择的元素,然后定义添加新数据时它的显示方式(这里您将使用enter().append().attr().transition().duration().attr() 模型)。然后您指定一般更新。然后你希望它如何通过exit()退出...
    • 感谢您的链接。我通读了其中的一些。根据我阅读的内容,如果以下是我在 SVG 中添加组的代码:

      var barGroup = d3.select("#" + chartId).selectAll("g.barChart") .append("g") .attr("class", "bar") .attr("id", chartId) .attr("style", "opacity:1.0")

      我应该能够添加以下转换? .transition().delay(1000).duration(3000).attr("style", "opacity:0.1")
      ?
    • 我建议为 transform 属性设置动画,它也适用于 元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多