javascript - 从 D3 库访问 svg

标签 javascript d3.js svg

所以我有一个从 D3 库的数据生成的 SVG 图像(3 个圆圈)。

var myData = [1,2,3];
var svgViewport = d3.select("body").append("svg").attr("width","600").attr("height","600"); 
var circleSelection = svgViewport.selectAll("circle").data(myData); 
var circleElements = circleSelection.enter().append("circle");

circleElements.attr("cx",function(d,i) { 
    return d * 100; 
})
    .attr("cy",function(d,i) { 
        return d * 50; 
    })
    .attr("r","35");

function greenBlue(d,i) {
    if (i % 2 === 0) { 
        return "green"; 
    }
    else { 
        return "blue"; 
    };
}

greenBlue(1,2);
var circleStyle = circleElements.style("fill",greenBlue);

我希望当我将鼠标悬停在某个元素上时它会改变颜色。我知道当元素位于 HTML 文件中时该怎么做,但我想知道它是如何实现的

document.getElementById("info").onmouseover = function() {
mouseOver()};

在这种情况下可以更换。

最佳答案

当然,请先阅读 d3 documentation on event handling ,这将带您查看 .on 方法的文档。因此,如果您想更改鼠标悬停时的颜色,可以使用 on 和 this:

circleElements.on("mouseover", function() {
  d3.select(this).style("fill", "green");
});

这个例子几乎是逐字的 the example in the documentation .

关于javascript - 从 D3 库访问 svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44398356/

相关文章:

svg - 缩放父元素时保留后代元素的大小

javascript - 将 DataURL 保存为 jpg

javascript - 页面加载时显示文本区域的所有行

javascript - 如何从javascript中的字符串中获取子字符串?

d3.js - 将 D3 Band Zoom 从 v3 升级到 v4

javascript - D3.js水平直方图

javascript - 用于带比例打印的 SVG

javascript - 在 Express.js 中,我是否应该返回响应?

javascript - 使用 D3 将 SVG Canvas 附加到主体以外的元素

javascript - Fabricjs svg解析错误