var dataset = [30,43,120,87,99,167,142] var width = 500, height = 500; var rectWidth = 30, rectStep= 35; var svg = d3.select("body").append("svg") .attr("width",width) .attr("height",height)
一、分别获取rect的update、enter、exit部分:
//获取矩形的update部分 var rectUpdate = svg.selectAll("rect") .data(dataset) //获取矩形的enter部分 var rectEnter = rectUpdate.enter() //获取矩形的exit部分 var rectExit = rectUpdate.exit()二、分别对rect的update、enter、exit进行操作
//rectUpdate处理 rectUpdate.attr("fill","steelblue") .attr("x", function (d,i) { return i*rectStep }) .attr("y",function(d){return height-d}) .attr("width",rectWidth) .attr("height",function(d){return d}) //rectEnter处理 rectEnter.append("rect") .attr("fill","steelblue") .attr("x", function (d,i) { return i*rectStep; }) .attr("y", function (d) { return height-d; }) .attr("width",rectWidth) .attr("height",function(d){return d}) //rectExit处理 rectExit.remove()
/** * Created by Silence_C on 2016/5/11. */ var dataset = [30,43,120,87,99,167,142] var width = 500, height = 500; var rectWidth = 30, rectStep= 35; var svg = d3.select("body").append("svg") .attr("width",width) .attr("height",height) function draw(){ //获取矩形的update部分 var rectUpdate = svg.selectAll("rect") .data(dataset) //获取矩形的enter部分 var rectEnter = rectUpdate.enter() //获取矩形的exit部分 var rectExit = rectUpdate.exit() //rectUpdate处理 rectUpdate.attr("fill","steelblue") .attr("x", function (d,i) { return i*rectStep }) .attr("y",function(d){return height-d}) .attr("width",rectWidth) .attr("height",function(d){return d}) //rectEnter处理 rectEnter.append("rect") .attr("fill","steelblue") .attr("x", function (d,i) { return i*rectStep; }) .attr("y", function (d) { return height-d; }) .attr("width",rectWidth) .attr("height",function(d){return d}) //rectExit处理 rectExit.remove() //获取文字的update var textUpdate = svg.selectAll("text") .data(dataset) //获取文字enter部分 var textEnter = textUpdate.enter() //获取文字的exit部分 var textExit = textUpdate.exit() //textUpdate处理 textUpdate.attr("fill","white") .attr("font-size","16px") .attr("text-anchor","middle") .attr("x",function(d,i){return i*rectStep}) .attr("y",function(d){return height-d}) .attr("dx",rectWidth/2) .attr("dy","1em") .text(function(d){ return d }) //textEnter处理 textEnter.append("text") .attr("fill","white") .attr("font-size","14px") .attr("text-anchor","middle") .attr("x",function(d,i){return i*rectStep}) .attr("y",function(d){return height-d}) .attr("dx",rectWidth/2) .attr("dy","1em") .text(function(d){ return d }) //textExit处理 textExit.remove(); } draw() function myadd(){ dataset.push(Math.floor(Math.random()*100)); draw() } function mysort(){ dataset.sort(d3.ascending) draw() }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>update\enter\exit的应用</title> </head> <body> <script src="d3.js"></script> <script src="js/datatrect.js"></script> <br/> <button type="button" onclick="mysort()"> 排序 </button> <button type="button" onclick="myadd()"> 增加数据 </button> </body> </html>