d3.js学习3
Enter-update-exit模式
select.data(data),代表selection图形与data数据的交集->Update Mode
select.data(data).enter(),代表data数据排除selection图形与data数据的交集->Enter Mode
select.exit,移除所有数据,代表selection图形的部分->Exit Mode
E-U-E即为d3.js的基础
数组数据绑定
var data=[10,15,24,46,13,6,96,12,44,61,17]; function render(data){ //进入 d3.select("body").selectAll("div.h-bar")//选择页面上所有即将生成的css为h-bar的元素 .data(data) .enter() .append("div") .attr("class","h-bar") .append("span");//用来显示当前值d //更新 d3.select("body").selectAll("div.h-bar") .data(data) .style("width",function(d){//设置柱状图的长度为d的3倍 return (d*3)+"px"; }) .select("span")//在span内输出d值 .text(function(d){ return d; }); //退出 d3.select("body").selectAll("div.h-bar") .data(data) .exit() .remove(); } setInterval(function(){ data.shift();//去除第一个元素,用于动态循环展示数据 data.push(Math.round(Math.random()*100));//在结尾处加一个随机数据,同样用于动态循环演示 render(data); },15000);//1.5秒每次循环更新数据 render(data);//初次展示数据
CSS:
<style type="text/css"> .h-bar { min-height: 15px; min-width: 10px; background-color: steelblue; margin-bottom: 2px; font-size: 11px; color: #f0f8ff; text-align: right; padding-right: 2px; } </style>
复杂数据绑定
var data=[ {width:10,color:23},{width:15,color:33}, {width:30,color:40},{width:50,color:60}, {width:80,color:22},{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 mode d3.select("body").selectAll("div.h-bar") .data(data) .enter() .append("div") .attr("class","h-bar") .append("span"); //exit mode d3.selectAll("body").selectAll("div.h-bar") .data(data) .exit() .remove(); //update mode d3.select("body").selectAll("div.h-bar") .data(data) .attr("class","h-bar") .style("width",function(d){ return (d.width*3)+"px"; }) .style("background-color",function(d){ return colorScale(d.color); }) .select("span") .text(function(d){ return d.width; }) } function randomValue(){ return Math.round(Math.random()*100); } setInterval(function(){ data.shift(); data.push({width:randomValue(),color:randomValue()}); render(data); },1500); render(data);
函数绑定
var data=[]; var next=function(x){ return 15+x*x; } var newData=function(){ data.push(next); return data; } function render(){ var selection=d3.select("#container") .selectAll("div") .data(newData); //enter selection.enter().append("div").append("span"); //exit selection.exit().remove(); //update selection.attr("class","h-bar") .style("width",function(d,i){ return d(i)+"px";//d相当于调用了函数newData,i为下标参数,从0开始 }) .select("span") .text(function(d,i){ return d(i); }); } setInterval(function(){ render(); },1500); render();
这是我的个人日记本