1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>过滤</title> 6 <script src="d3.js"></script> 7 </head> 8 <style> 9 .h-bar { 10 min-height: 15px; 11 min- 10px; 12 background-color: steelblue; 13 margin-bottom: 2px; 14 font-size: 11px; 15 color: #f0f8ff; 16 text-align: right; 17 padding-right: 2px; 18 } 19 .selected{ 20 background-color: pink; 21 } 22 </style> 23 24 <body> 25 <script> 26 // 定义数据 27 let data = [ 28 { expense: 10, category: "Retail" }, 29 { expense: 15, category: "Gas" }, 30 { expense: 30, category: "Retail" }, 31 { expense: 50, category: "Dining" }, 32 { expense: 80, category: "Gas" }, 33 { expense: 65, category: "Retail" }, 34 { expense: 55, category: "Gas" }, 35 { expense: 30, category: "Dining" }, 36 { expense: 20, category: "Retail" }, 37 { expense: 10, category: "Dining" }, 38 { expense: 8, category: "Gas" } 39 ] 40 function render(data, category) { 41 // 进入 42 d3.select("body").selectAll('div.h-bar') 43 .data(data) 44 .enter() 45 .append("div") 46 .attr('class', 'h-bar') 47 .append('span') 48 // 退出 49 d3.select("body").selectAll('div.h-bar') 50 .data(data) 51 .exit() 52 .remove() 53 // 更新 54 d3.select("body").selectAll('div.h-bar') 55 .data(data) 56 .attr("class", "h-bar") //为了初始化下样式 57 .style('width', function(d) { 58 return (d.expense*5) + 'px' 59 }) 60 .select("span") 61 .text(function(d) { 62 return d.category; 63 }); 64 65 d3.select("body").selectAll('div.h-bar') 66 .filter(function(d, i) { 67 return d.category == category 68 }) 69 .classed("selected", true) 70 } 71 72 render(data); 73 function select(category){ 74 render(data, category); 75 } 76 </script> 77 <div> 78 <button onclick="select('Retail')">Retail</button> 79 <button onclick="select('Gas')">Gas</button> 80 <button onclick="select('Dining')">Dining</button> 81 <button onclick="select()">Clear</button> 82 </div> 83 </body> 84 85 </html>