《d3.js可視化實戰手冊》筆記javascript
官網:html
http://d3js.org/java
範例:git
https://github.com/mbostock/d3/wiki/Gallerygithub
引用:app
//在線引用 <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> //或下載到本地 <head> <meta charset="utf-8"> <title>D3.js galance</title> <script src="d3.min.js"></script> </head>
開始:this
<body> <p id='target'></p> <script type="text/javascript"> d3.select("p#target").text("Hello World!"); </script> </body>
d3.select實現單個元素選取htm
select.attr,讀取/設置元素屬性blog
<p id='target'></p> <script type="text/javascript"> var res=d3.select("p#target").attr("id"); document.write(res); </script> //結果爲target
<p></p> <script type="text/javascript"> d3.select("p").attr("id","p1"); var res=d3.select("p").attr("id"); document.write(res); </script> //將p的id設爲p1,並輸出p的id
select.classed,添加/刪除元素類索引
<p class="p1"></p> <script type="text/javascript"> var res=d3.select("p").classed("p1"); document.write(res); </script> //檢測該元素是否屬於p1類,返回布爾值
<p></p> <script type="text/javascript"> var res=d3.select("p").classed("p1",true); </script> //爲P標籤添加p1這個類
<p class="p1"></p> <script type="text/javascript"> d3.select("p").classed("p1",function(){return false;}); var res=d3.select("p").classed("p1"); document.write(res); </script>
//爲P標籤移除p1這個類
select.style,樣式選擇器
<p></p> <script type="text/javascript"> var res=d3.select("p").style("font-size"); document.write(res); </script> //輸出p style的字號
<p></p> <script type="text/javascript"> var res=d3.select("p").style("font-size","16px"); document.write(res); </script>
//設定字號爲16
select.text,選擇或設置文本內容
<p>be my valentine</p> <script type="text/javascript"> var res=d3.select("p").text(); document.write(res); </script> //選擇文本內容
<p>be my valentine</p> <script type="text/javascript"> d3.select("p").text("be my darling"); var res=d3.select("p").text(); document.write(res); </script> //將原來的替換爲新的
select.html,選擇或更改元素內的html
<p>be my valentine</p> <script type="text/javascript"> var res=d3.select("p").html(); document.write(res); </script> //獲取p元素內容
<p>be my valentine</p> <script type="text/javascript"> d3.select("p").html("<b>be my darling</b>"); var res=d3.select("p").html(); document.write(res); </script> //設置標籤中html的內容
多元素選擇器
<div>div1</div></br> <div>div2</div></br> <div>div3</div></br> <script type="text/javascript"> d3.selectAll("div").style("border","2px solid blue"); </script>
多元素路由迭代選集(選取子元素)selectAll().each(function(d,i){//do sth})
<div></div></br> <div></div></br> <div></div></br> <script type="text/javascript"> d3.selectAll("div") .style("border","2px solid blue") .each(function(d,i){ d3.select(this).append("h1").text(i); }) </script>
each方法包括兩個可選參數d & i,以及一個隱含參數this, this指向當前DOM引用的元素,d表示當前元素數據綁定,i表示索引值,0開始,遞增1.