d3.js中的选择元素

    xiaoxiao2021-04-16  53

    在 D3 中,用于选择元素的函数有两个:

    d3.select():是选择所有指定元素的第一个d3.selectAll():是选择指定元素的全部

    这两个函数返回的结果称为选择集。

    怎么使用这2个函数呢?看代码:

    var body = d3.select("body"); //选择文档中的body元素 var p1 = body.select("p"); //选择body中的第一个p元素 var p = body.selectAll("p"); //选择body中的所有p元素 var svg = body.select("svg"); //选择body中的svg元素 var rects = svg.selectAll("rect"); //选择svg中所有的svg元素

    下面我们看看这2个函数源码,在d3.js的985和990行,如下:

    d3.select = function(node) { var group = [ typeof node === "string" ? d3_select(node, d3_document) : node ]; group.parentNode = d3_documentElement; return d3_selection([ group ]); }; d3.selectAll = function(nodes) { var group = d3_array(typeof nodes === "string" ? d3_selectAll(nodes, d3_document) : nodes); group.parentNode = d3_documentElement; return d3_selection([ group ]); }; 这里可以看到,首先得到一个group对象 typeof node === "string" 判断node类型为string的,如果为真,分别返回: d3_select(node, d3_document)和d3_selectAll(nodes, d3_document) node是你要选中的元素,那么出现的 d3_document和d3_documentElement分别是什么呢?请看下面这行代码的定义: var d3_document = document, d3_documentElement = d3_document.documentElement, d3_window = window; 从这儿就应该明白了,document和document.documentElement,这是dom操作。注:这是html中的知识

    每个载入浏览器的 HTML 文档都会成为 Document 对象。

    Document 对象使我们可以从脚本中对 HTML 页面中的所有元素进行访问。

    提示:Document 对象是 Window 对象的一部分,可通过 window.document 属性对其进行访问。

    继续往下看,最后通过d3_selection()函数返回。 function d3_selection(groups) { d3_subclass(groups, d3_selectionPrototype); return groups; }然后用到d3_subclass()函数,直接看代码: d3_selectionPrototype是这样定义的: var d3_selectionPrototype = d3.selection.prototype = []; 继续看 var d3_subclass = {}.__proto__ ? function(object, prototype) { object.__proto__ = prototype; } : function(object, prototype) { for (var property in prototype) object[property] = prototype[property]; };这是什么?见过吗?其实在 Javascript中Function,Object,Prototypes,__proto__等概念是很常用的。不懂得自己查查。 可以认为__proto__是用来扩展Function的,扩展出来的函数,可以直接调用,不需要new出对象才能用,同时对象是不会扩展通过__proto__扩展的方法或属性的。 通过以上,我们对这2个函数的调用方式有了一个清楚的了解,后续直接应用就可以了。select返回一个元素;selectAll()返回一个数组,然后遍历使用。 最后上一个小demo: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>HelloWorld</title> <script src="../libs/d3.min.js" charset="utf-8"></script> </head> <body> <p>Hello World 1</p> <p>Hello World 2</p> </body> </html> <script> //d3.select("body").selectAll("p").text("www.ourd3js.com"); //选择<body>中所有的<p>,其文本内容为 www.ourd3js.com,选择集保存在变量 p 中 var p = d3.select("body") .selectAll("p") .text("www.ourd3js.com"); //修改段落的颜色和字体大小 p.style("color","red") .style("font-size","72px"); </script>

    转载请注明原文地址: https://ju.6miu.com/read-672090.html

    最新回复(0)