简体   繁体   中英

d3js - On duplicating SVG element, resulting wrong output

I created a svg graphics using d3js . and i have a scenario to show the same graphics on click on the popup, so i am duplicating with another div element on click of the existing svg element.

it works. but the result is wrong. the appending new svg is pre-pending and being as first element instead of last.

on my first element i have opacity as 0.5' in the duplicated element i have the opacity:1`, and the color changing to "blue" but it not work in correct way. here is my code :

var w = 100;
var h = 100;
var padding = 5;

var svg = d3.select('#svg1').append('svg')
    .attr({
        width: w,
        height: h
    });

svg.append('rect')
    .attr({
        width: w,
        height: h,
        fill: 'red'
    });

var little = svg.selectAll('rect.small')
    .data(d3.range(9));



little.enter().append('rect')
    .attr({
        width: w / 3 - padding * 2,
        height: h / 3 - padding * 2,
        fill: 'grey',
        x: function(d) { return d % 3 * (w / 3) + padding; },
        y: function(d) { return ~~(d / 3) * (h / 3) + padding; }
    });

var group = svg.append("svg:g").attr("id", "textInfo")
.attr("transform", "translate("+ w/2+","+h/2+")");

var text = group.append("text").text("Testing")
    .attr("class", "inform")
    .style({
    "text-anchor" : "middle",
    "fill" : "yellow",
    "opacity" : 0.5
});

function addAnother() {
    var content = d3.select("#svg1").html();
    var div = d3.select('#svg2').html(content);
    //adding text

    d3.select('.inform').style({
        "fill" : "blue",
        "opacity" : 1
    })
}

svg.on('click', addAnother);

Online Demo

The second element is properly appended, but when you select the elements with the inform class, you actually end up selecting and changing the first element instead.

If you want to alter the style of the second element(the appended one), you have to change the selector from:

d3.select('.inform').style({
    "fill" : "blue",
    "opacity" : 1
})

to:

d3.select('#svg2 .inform').style({
    "fill" : "blue",
    "opacity" : 1
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM