javascript - 如何在 D3 中悬停时为图像添加边框

标签 javascript html css d3.js

我正在使用 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/

相关文章:

javascript - 使用 Backbone.js 和 Express.js 构建应用程序

javascript - 简单打印示例

html - 在背景图像上居中叠加文本

javascript - 如何在javascript中创建行高的倍数?

javascript - 在 Angular 5 中使用 Observable.ForkJoin 重复 Http 请求

javascript - GroupBy 使用 underscore.js 使用嵌套 JSON 对象

javascript - [[范围]] 和执行上下文

html - 只有一些 CSS 在移动设备上加载,在桌面上完美运行

javascript - 为什么我在新打开的窗口中看不到字形图标?

jquery - 使用 jquery 更改多个对象