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

12 篇文章 1 订阅
9 篇文章 2 订阅

d3.js学习笔记-02

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/false
  • selection.node() // 返回第一个非空元素,为空则为null
  • selection.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.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值