d3.js学习笔记-02(选择集)

tech2023-01-24  55

d3.js学习笔记-02

目录

d3.js学习笔记-021. 选择元素1.1 select1.2 selectAll 2 选择集(selection)2.1 查看选择集状态2.2 设置/获取属性selection.attr()selection.classed()selection.style()selection.property()selection.text()selection.html() 2.3 插入、删除、添加元素selection.insert()selection.remove()selection.append() References

1. 选择元素

1.1 select

select返回匹配选择其的第一个元素,即使有多个元素符合,也只选择第一个元素

d3.select("body"); //选择body元素 d3.select("#important");//选择id为important的元素 d3.select(".content"); //选择类为content的第一个元素

参数为已经被DOM API选择的元素

var important = document.getElementById("important"); d3.select(important) ; //此时不加引号,参数为一个变量

对选择的元素进一步筛选,使用连续的selectselectAll.

d3.select("body") .selectAll("p");// 选择body中所有的p元素 d3.selectAll("ul li"); //选择ul中所有的1i元素

1.2 selectAll

seletAll返回匹配选择器的所有元素。

a3.selectAll("p"); //选择所有的p元素 a3.selectAll(".content": //选择类为content的所有元素 d3.selectAll("ul li"); //选择ul中所有的1i元素

2 选择集(selection)

选择集:select和selectAll返回的对象

2.1 查看选择集状态

selection.empty() // 返回true/falseselection.node() // 返回第一个非空元素,为空则为nullselection.size() // 返回选择集中的元素个数

2.2 设置/获取属性

selection.attr()

selection.attr(name[,value]):name为属性名称,value为属性值。如果省略value,则返回属性值;否则设置属性name的值为value。 svg.append("circle") //在<svg>中添加<circle>标签 .attr("cx"."50px") // 设置属性cx的值为50px .attr("cy","50px") //设置属性cy的值为50px .attr("r","50px") //设置属性r的值为50px .attr("fi11", "red"); //设置属性fi11的值为red .attr("class","red bigsize") // 设置多个类,类名之间用空格隔开 var cx = d3.select("circle".attr("cx"): console.log(cx); //50px

selection.classed()

selection.classed(name[,value]):设置/获取选择集的CSS类,name为类名,value为bool值,表示开启或关闭类。如果省略value,则返回bool值,表示类是否开启。 d3.select("p") .classed ("red",true) //1开启red类 .classed ( "bigsize" , false);//不开启bigsize类 // 同时修改多个类 .classed( "red": true, "bigsize":true });//写在一个对象里 .classed("red bigsize",true); //用空格分开写在一起

selection.style()

selection.style(name[,value[, priority]]):name为样式名称,如颜色、字体等;value为样式的值。如果省略name后面的参数,则返回样式的值。 d3.select ("p") .style ("color", "red") .style("font-size","30px"); // 同时设定多个样式的值 .style({"color" : "red" , "font-size":" 30px" }):

selection.property()

selection.property(name[,value]):设置/获取选择集的属性,name为属性名,value为属性值。 d3.select("#fname").property ("value"); //文本框的value属性、复选框等不能通过attr来获取

selection.text()

selection.text([value]):设置/获取选择集的文本内容,不会返回元素包含的内部的标签。

selection.html()

selection.html([value]):设置/获取选择集内部的HTML内容,包含元素内部的标签。

2.3 插入、删除、添加元素

selection.insert()

selection.insert(name[, before]):在指定的元素之前插入一个元素

selection.remove()

selection.remove():删除选择集中的元素

selection.append()

selection.append(name):在选择及的末尾添加一个元素

References

[1] 吕之华.精通D3.js:交互式数据可视化高级编程[M].北京:电子工业出版社,2015∶61-67.

最新回复(0)