这书买了一个月了,终于开封了。
D3.js的官网,看官网最新的版本已经到5.7了。
D3.js - Data-Driven Documentsd3js.org之前对D3.js的印象完全以为它是一个图形库,类似于echart.js那种,各种安利D3.js的广告也都打的是可视化的关键词。
不读书只能被扇醒啊,应该类比成jQuery才对。至少链式的操作跟jQuery是一模一样的。
Hello World
先看一个Hello World感受一下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>D3 Study</title>
<script src="d3.js"></script>
</head>
<body>
<script>
function SimpleWidget(spec) {
var instance = {}
var headline, description
instance.render = function() {
var div = d3.select('body').append('div')
div.append('h3').text(headline)
div.attr('class', 'box')
.attr('style', "color:" + spec.color)
.append('p')
.text(description)
return instance
}
instance.headline = function(h) {
if(!arguments.length) return headline
headline = h
return instance
}
instance.description = function(d) {
if(!arguments.length) return description
description = d
return instance
}
return instance
}
var widget = SimpleWidget({color: "#6495ed"})
.headline("Simple Widget")
.description("This is a simple widget demonstrating functional javascript")
widget.render()
</script>
</body>
</html>
github上的中文手册也不错
d3/d3github.com选择器
这跟jQuery一毛一样啊,DOM操作的话选择器确实是基础。
选取单个元素
d3.select( )
d3.select("p#target")
选择完了之后可以链式地跟attr、classed、style、text、html各种方法,直接看栗子
d3.select("p").attr("foo", "bar") //设置foo属性
d3.select("p").attr("foo") //获得foo属性
d3.select("p").classed("goo") //class里是否有goo
d3.select("p").classed("goo", true) //这才是设置goo
d3.select("p").classed("goo", function() { return false}) //用个方法,移除goo
//后面用法都跟classed类似了
d3.select("p").style("font-size")
d3.select("p").style("font-size", "10px")
d3.select("p").style("font-size", function() { return parseFloat(d3.select(this).style('font-size')) + 10 + 'px'})
d3.select("p").text()
d3.select("p").text("Hello")
d3.select("p").text(function(){ return Date()})
d3.select("p").html()
d3.select("p").html("<b>Hello</b>")
d3.select("p").html(function() { return "<b>Hello</b>"})
选取多个元素
d3.selectAll( )
迭代元素
d3.selectAll("div")
.attr("class", "red box")
.each(function(d, i){
d3.select(this).append("h1").text(i)
})
举一反三,查了下API,没有map,但是有filter
子选择器
要么使用css的>选择器来选择子元素,要么通过级联继续调用select来选择子元素,至于我们熟悉的jQuery里的children( ),查了一下,在d3里存在于别的对象上
d3.select("#section1 > div")
d3.select("#section1").select("div")
D3.js里的级联调用,返回的都是当前操作或者变化的元素,所以会看到如下的代码
body.append("section")
.attr("id", "section1") //section
.append("div")
.attr("class", "blue box") //div
.append("p")
.text("FooBar") //p
获得原始DOM对象
通过D3.js操作后的对象并不是原始DOM对象,这也跟jQuery一样,jQuery里只要调用数组索引[index]或者get(index)方法就能获得,在D3.js里要通过nodes( )方法
d3.selectAll("tr").nodes()