简体   繁体   中英

d3 mouseover event wont fire if I append svg to a div

I'm trying to get a simple mouseover to work on some rectangles in d3. If I append the SVG to "body" everything works just fine (first line of code). If I change the select to ".chart1" instead of "body" the mouseovers don't work. Has anyone seen this before?

var chart = d3.select(".chart1").append("svg")
  .attr("width", 250)
  .attr("height", 50);

data = ["a", "b", "c",]

for(var i = 0; i < data.length; i++){
            var rect = chart.append("rect")
              .attr("x", 20*i)
              .attr("y", 10)
              .attr("width", 15)
              .attr("height", 15)

chart.selectAll('rect')
    .on("mouseover", function() {
        d3.select(this)
            .attr("opacity", .5)
    })
    .on("mouseout", function() {
        d3.select(this)
            .attr("opacity", 1)
    });

jsfiddle: https://jsfiddle.net/jasonleehodges/um5f5ysv/

The problem is not because you are appending svg to body or div with class .chart1

The problem of mouseover not working is in here.

var chart = d3.select(".chart1").append("svg")
  .attr("width", 250)
  .attr("height", 50)
  //.style("pointer-events", "none");//WHY DISABLE MOUSE EVENT ON SVG

Fix would be to remove .style("pointer-events", "none"); and it will work on all the cases without any anomaly.

Working code here

On another note you should not use a for loop, well that's not the d3 way(as put by @Gerardo Furtado).

so your code with for :

for(var i = 0; i < data.length; i++){
            var rect = chart.append("rect")
              .attr("x", 20*i)
              .attr("y", 10)
              .attr("width", 15)
              .attr("height", 15)

instead should be

var rect = chart.selectAll("rect").data(data).enter().append("rect")
              .attr("x", function(d,i){return 20*i})
              .attr("y", 10)
              .attr("width", 15)
              .attr("height", 15)
              .attr("fill", "#cc004c")
              .attr("title","NBC")
              .attr("data-toggle","tooltip")

working code here

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