我正在使用 D3,其中 Pack 布局的叶子由这样添加的图像表示:
svg.selectAll("image.leaves")
.data(nodes, keyFunction)
.enter().append("g")
.append("image")
.attr("class", "leaves")
.attr("xlink:href", function (d) {
if (d.fileType == "Document")
return "document.png";
return "other.png";
});
我想在鼠标悬停时为该图像添加黑色边框,但我无法通过以下方法实现:
.leaves:hover { border: 1px solid #000; }
因为它什么都不做。
如果有人能在正确的方向上帮助我,我将不胜感激。
最佳答案
不幸的是,SVG 元素不接受与 HTML 元素相同的样式属性。您可以找到 SVG 元素的有效样式属性列表 HERE .
要制作边框,您可以使用 <rect>
与您的图像尺寸相同的元素,并将其添加到 <g>
您在输入选择中创建的元素:
// store the entering group as a variable
var imageEnter = svg.selectAll('.leaves')
.data(nodes, keyFunction)
.enter().append('g')
.attr('class', 'leaves');
// append the image
imageEnter.append('image')
.attr('xlink:href', function(d) {
return d.fileType === 'Document' ? 'document.png' : 'other.png';
});
// append the border rect
imageEnter.append('rect')
.attr('class', 'image-border')
.attr('width', widthOfYourImage)
.attr('height', heightOfYourImage);
现在您可以使用您的 css 来更改 stroke
悬停时边框矩形的属性。因为它是 <rect>
,当光标悬停在它的任何部分上时,悬停状态将处于事件状态,即使它的填充设置为透明,也不需要使用父级的悬停状态来更改子级的样式。漂亮而简单:
.image-border {
fill: transparent;
stroke: transparent;
shape-rendering: crispEdges;
}
.image-border:hover {
stroke: black;
}
HERE是一个简化的例子。
关于javascript - 如何在 D3 中悬停时为图像添加边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25393336/