foreignObject中的背景图像隐藏了Firefox上的其他svg元素

时间:2017-09-07 00:03:59

标签: javascript html css d3.js svg

我无法在使用d3创建的可视化中添加横幅。我想添加横幅,然后在横幅上添加文字。这适用于Chrome(文本呈现在图像的“顶部”),但在Firefox上,它看起来像是在文本顶部呈现图像。任何人都知道为什么这在Chrome中有效但在Firefox中无效,有没有办法可以在Firefox中实现相同的效果?

    var margin = {
    top: 155,
    right: 3,
    bottom: 3,
    left: 3
  },
  width = $(window).width() - margin.left - margin.right,
  height = $(window).height() - margin.top - margin.bottom,
  formatNumber = d3.format(",d"),
  transitioning;

var x = d3.scale.linear()
  .domain([0, width])
  .range([0, width]);

var y = d3.scale.linear()
  .domain([0, height])
  .range([0, height]);

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
  .style("shape-rendering", "crispEdges");

var grandparent = svg.append("g").attr("class", "grandparent");

grandparent.append("rect")
  .attr("y", -margin.top)
  .attr("width", width)
  .attr("height", margin.top);

grandparent.append("foreignObject")
.attr("y", -margin.top)
  .attr("width", width)
  .attr("height", margin.top)
  .append("xhtml:div")
  .attr("class", "bannerDiv");

grandparent.append("text")
  .attr("x", 6)
  .attr("y", (-1 / 8) * margin.top)
  .attr("dy", ".75em")
  .style("fill", "#A5D867")
  .text("The text here");

function text(text) {
  text.attr("x", function(d) {
      return x(d.x) + 6;
    })
    .attr("y", function(d) {
      return y(d.y) + 6;
    });
}

请看这个jsfiddle的例子: https://jsfiddle.net/rmw6snj6/

1 个答案:

答案 0 :(得分:3)

这是Firefox中的已知错误:https://bugzilla.mozilla.org/show_bug.cgi?id=984312

在错误报告中,一个给定的解决方法是将foreignObject的转换设置为translate(0,0)

input:checked + svg foreignObject {
  transform: translate(0, 0);
}
.bannerDiv {
  width: 100%;
  height: 100%;
  background-image: url('http://www.newdesignfile.com/postpic/2011/10/header-banner-design_64599.jpg');
  -webkit-background-size: 100% 100%;
  -moz-background-size: 100% 100%;
  -o-background-size: 100% 100%;
  background-size: 100% 100%;
}

body {
  background: #bbb;
}
<label>workaround</label><input type="checkbox" checked/>
<svg width="535" height="484">
  <g transform="translate(3,155)" style="shape-rendering: crispedges;">
    <g class="grandparent">
      <rect y="-155" width="529" height="155"></rect>
      <foreignObject y="-155" width="529" height="155">
        <div class="bannerDiv"></div>
      </foreignObject>
      <text x="6" y="-19.375" dy=".75em" style="fill: rgb(165, 216, 103);">The text here</text>
    </g>
  </g>
</svg>