效果如图所示,demo连接地址
源码连接地址javascript
其实这个例子也很简单,用到的也只是d3的基础部分,咱们要把必定间隔请求过来的数据进行排序, 并生成dom元素,同时重用原来和新数据相对应的dom元素,删除不对应的,说的有点绕,表达能力不行,其实说到这明白人都能看出来了,这要用到D3选择器的enter()以及exit()方法,至于动画用到css3的transition.
首先,我准备了两份数据,一份是一个对象数组叫data,另外一份也是一个对象数组叫anther_data,两份数据结构同样,内容不一样,设定每个方块的位置和动画样式,css
.site { box-sizing: border-box; -webkit-transition: 1s ease-out; transition: 1s ease-out; overflow: hidden; background: green; padding: 10px 20px; position: absolute; width: 200px; height: 100px; } #index_0,#index_1....
其次,根据data数据经过selection.enter()方法生成初始的dom元素,并编写go函数根据接收的data对页面进行重绘和重排,在这里Key函数起到关键做用了,根据url相同,决定哪些dom须要从新生成,哪些dom须要删除,(关于Key 函数能够参考我以前的博文)html
var sites = d3.selectAll(".site") .data(data, function(d) { return d.url; });
删除不须要的dom前端
sites.exit().remove();
经过改变留下来的dom元素的id来改变它的位置java
sites.attr("id", function(d, i) { return "index_" + i; });
生成新的dom元素css3
sites.enter() .append("div") .attr("class", "site") .attr("id", function(d, i) { return "index_" + i; }) .text(function(d) { return d.url; });
最后, 两秒运行一次go函数加载不一样的数据git
setInterval(function() { if(temp) { go(another_data); } else { go(data); } temp = !temp; }, 2000);
但愿个人文章能帮助到你,更多资料请翻阅d3js.org,
我是朱现明,任职于精硕科技可视化部门前端开发,更多精彩的文章即将奉上.github