3

D3 的选择操作是通用的(如attr),它接受一个值,或者一个传递数据的函数。我想根据当前选择设置一些样式参数。

来自文档:据我了解,以下场景将起作用

sel.style("stroke", "#000")
sel.style({"stroke": "#000", "stroke-width": "0.5"})
sel.style("stroke", function(d){return "#000"})

但是,我需要的是获取 fn 返回的对象。

var fn = function(d){
return {"stroke": "#000", "stroke-width": "0.5"}
}
sel.style( fn)

上面的例子,我不做任何事情d,但是,在我的情况下,我会根据d通过做出决定。

我敢肯定,我可以做类似的事情,

sel.style(`fill`, fillFn)
sel.style(`stroke`, strokeFn)

但是,我正在尝试使我的代码通用,所以我可能不知道我需要提前设置什么样式。

编辑:

我也试过selection.property,,

sel.property("style", fn);

但有错误

TypeError: Object [object Array] has no method 'property'

但是,在同一个选择中,如果我这样做

sel.style({"stroke": "#000", "stroke-width": "0.5"})

它工作正常。有什么问题?

4

2 回答 2

5

在这种情况下,我将使用该.each()函数(或者可能.call())在每个(或一次全部)选定元素上运行一个函数。在此功能中,您可以根据数据或其他内容添加样式、属性等。

基本代码如下所示。

sel.each(someFunc);
function someFunc(d) {
    if(d.something) { d3.select(this).style("foo", "bar"); }
    if(d.somethingElse) { d3.select(this).attr("bar", "foo"); }
}
于 2013-10-16T19:25:21.763 回答
1

我的回答几乎与 css 有关,但我认为解决问题是个好主意。

    d3.selection.prototype.css = function (...arr) {
        if (arr.length === 2) {
            this.style(arr[0], arr[1]);
        } else if (arr.length === 1 && typeof arr[0] === 'object') {
            let properties = arr[0];

            for (let prop in properties) {
                this.style(prop, properties[prop]);
            }
        }
        return this;
    };

用途:

    d3.select('body').css('text-decoration', 'underline').css({
        'color': '#f00',
        'font-size': '20px'
    });

p / s:大约2小时前我刚刚学习d3。祝你好运 :)

于 2017-05-10T02:05:33.773 回答