简体   繁体   中英

D3 Mouseover/Mouseout Conflict

I'm having an issue with mouseover and mouseout events in d3.

I have built an area graph and at each "data point" I have appended a circle. These circles are hidden (by setting opacity to 0) on load. Then, when you mouse over an area, it shows the circles relating to that layer.

I now need to make it so that when you hover over a circle, it grows a bit larger. However, when mousing over the circle, it triggers the mouseout event for the area (hiding the circles).

Is there any way that the events can be set so that the mouseout event doesn't fire until the mouse enters another layer or leaves the svg entirely?

Here is the current transition code that I have:

var svg = d3.select('svg');

svg.selectAll('.data-circles')
    .attr('opacity', 0);

svg.selectAll('.layer')
    .attr('opacity', 1)
    .on('mouseover', function (d, i) {
        svg.selectAll('.data-circles')
            .transition()
            .duration(250)
            .attr('opacity', function (d, j) {
                return j == i ? 1 : 0;
            });
    }).on('mouseout', function (d, i) {
        console.log(d, i);
        svg.selectAll('.data-circles')
            .transition()
            .duration(250)
            .attr('opacity', 0);
    });

    var dataCircle = svg.selectAll('.data-circle');

    dataCircle.on('mouseover', function (d, i) {
        d3.select(this)
            .transition()
            .duration(500)
            .attr('r', 8)
            .attr('stroke-width', 4);
    }).on('mouseout', function () {
        d3.select(this)
            .transition()
            .duration(500)
            .attr('r', 4)
            .attr('stroke-width', 2);
    });

And here is a link to the code on Jsfiddle

Thanks,

You can simply remove the mouseout handler (and rename mouseover to mouseenter for efficiency):

.on('mouseenter', function (d, i) {
        svg.selectAll('.data-circles')
            .transition()
            .duration(250)
            .attr('opacity', function (d, j) {
                return j == i ? 1 : 0;
            });
    });

This sets the correct opacity for the correct circles and doesn't interfere with the highlighting of individual circles. The difference to your previous interaction model is that the circles remain there even if the cursor leaves the plot area -- you could fix that by attaching a mouseout handler to the plot area/SVG.

Complete demo 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