D3-2 进来,更新,退出模式例子(对象数组作为数据)
D3-2 进入,更新,退出模式例子(对象数组作为数据)
啥都不写了,都在实例中了。
啥都不写了,都在实例中了。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style type="text/css"> .h-bar { background: green; margin-top: 5px; color: "#000"; } </style> <script type="text/javascript" src="/angularJs/js/d3_v2.js"></script> <script type="text/javascript"> var data = [ {width:10,color:23}, {width:15,color:33}, {width:30,color:40}, {width:50,color:60}, {width:80,color:22}, {width:65,color:10}, {width:55,color:5}, {width:30,color:30}, {width:20,color:60}, {width:10,color:90}, {width:8,color:10} ]; //随机获取一定范围的颜色值 var colorScale = d3.scale.linear().domain([0,100]).range(["#add8e6","blue"]); function render(data){ //enter d3.select("body").selectAll("div.h-bar") .data(data) .enter() //把没有绑定图片的数据全部选择出来(进行图片的绑定) //just only data .append("div") .attr("class","h-bar") .append("span"); //更新 d3.select("body").selectAll("div.h-bar") .data(data) .attr("class","h-bar") .style("width",function(d){ return (d.width + 5) + "px"; }) .style("background-color",function(d){ return colorScale(d.color); }) .select("span") .text(function(d){ return d.width; }) //退出 d3.select("body").selectAll("div.h-bar") .data(data) .exit() //把没有绑定数据的图片选择出来 //just only image .remove(); } function randomValue(){ return Math.round(Math.random() * 100); } //每隔1.5s调用 setInterval(function(){ data.shift();//更改数据,去掉数组的第一个元素 //更改数据,给数组末尾添加一个随机的数据 data.push({width:randomValue(),color:randomValue()}); render(data); },1500); render(data); </script> </head> <body> </body> </html>