在 Javascript 中设置 svg 填充属性

Setting svg fill attribute in Javascript

初学者的问题。为什么当我尝试更改我的 svg 属性时颜色变量 color.svg 不起作用?其他一切都有效:其他颜色(用于稍后添加的圆圈),以及 svg 的大小(sizing taken from here)。

常量:

// colors
var color = {svg: "black", 
             drop0: "rgba(204, 204, 255, 1)",
             drop1: "orange"};

// margins
var margin = {top: 20, right: 10, bottom: 20, left: 10};
var width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

现在我制作了一个 svg 并尝试设置属性。

// svg
var svg = d3.select("body").append("svg")
   .attr({width: width + margin.left + margin.right,
          height: height + margin.top + margin.bottom,
          fill: color.svg})
   .append("g")
   .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// followed by stuff about adding shapes, etc, which work

我不想在 CSS 中设置它。浏览器不会抛出任何错误。我已经注释掉了除了这些行之外的所有内容,而且 svg 仍然不是黑色。

@meetamit 在评论中帮助我意识到在 SVG 上添加填充只会影响 SVG 中包含的 svg 图形。 SVG 填充属性不会改变 SVG 的颜色。 @JSBob 提供了两种方法:添加一个矩形并设置填充,或者在 CSS.

中设置 SVG 的 background-color

SVG 的容器没有属性 "fill",而是 "style"。像这样替换它:

var color = {
  svg: "black",
  drop0: "rgba(204, 204, 255, 1)",
  drop1: "orange"
};

// margins
var margin = {
  top: 20,
  right: 10,
  bottom: 20,
  left: 10
};
var width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;
//Now I make an svg and try set attributes.

// svg
var svg = d3.select("body").append("svg")
  .attr("width", 900)
  .attr("height",600)
  .style("background-color", color.svg)  //  <---- HERE
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

Here de jsfiddle

并检查这个:https://css-tricks.com/cascading-svg-fill-color/