【问题标题】:Style of axis tick labels in d3.jsd3.js 中轴刻度标签的样式
【发布时间】:2018-02-11 22:59:40
【问题描述】:

以下脚本创建一个带有三个标签和一个标题的点刻度轴。 body css 选择器定义了 body 中所有文本元素的 font-family 和 font-size。虽然轴标题受 css 规则的影响,但轴刻度标签不受影响,尽管它们本身就是文本元素。我知道我可以使用 .axis 文本选择器设置刻度标签样式。也许我在这里遗漏了一些明显的东西,但是是什么阻止了刻度标签与正文选择器一起呈现?

代码如下:

<!doctype html>
<meta charset="utf-8">

<script src="d3.min.V4.js"></script>

<style>

body {
  font-family: Courier;
  font-size: 18px;
}

</style>

<body>

</body>

<script>

var margin = {top: 20, right: 60, bottom: 40, left: 70},
    width = 600,
    height = 100;

var svg = d3.select('body').append('svg')
                       .attr('width', width)
                       .attr('height', height);

var xScale = d3.scalePoint().domain(["blue", "red", "green"]).range([margin.left, width-margin.right]);

// Add the x Axis
 svg.append("g")
     .attr("transform", "translate(0," + (height - margin.bottom) + ")")
     .attr("class", "axis")
   .call(d3.axisBottom(xScale)
     );

//x axis title
svg.append('text')
   .text('Colors')
   .attr('x', width/2)
   .attr('y', height - 5)
   .style("text-anchor", "middle");


</script>

【问题讨论】:

    标签: javascript css d3.js svg


    【解决方案1】:

    正如 Gerardo 所提到的,API 将默认使用填充 #000 进行绘制。 解决方法是重新选择文本并重新设置样式。 看起来像这样:

    var xScale = d3.scalePoint().domain(["blue", "red", "green"]).range([margin.left, width-margin.right]);
    
    // Add the x Axis
    var xTicks = svg.append("g")
         .attr("transform", "translate(0," + (height - margin.bottom) + ")")
         .attr("class", "axis")
       .call(d3.axisBottom(xScale)
         );
    
    xTicks.selectAll('text').attr('fill', function(d){
        return d;
      });
    

    【讨论】:

      【解决方案2】:

      根据API,轴生成器自动设置容器g元素中刻度的字体大小和字体系列,这是默认样式(从API的示例中复制的代码):

      //styles applied to the outer g element:
      <g fill="none" font-size="10" font-family="sans-serif" text-anchor="middle">
          <path class="domain" stroke="#000" d="M0.5,6V0.5H880.5V6"></path>
          <g class="tick" opacity="1" transform="translate(0,0)">
              <line stroke="#000" y2="6" x1="0.5" x2="0.5"></line>
              <text fill="#000" y="9" x="0.5" dy="0.71em">0.0</text>
          </g>
          //etc...
      </g>
      

      因此,由于特殊性和优先级规则,这种样式似乎优于您的body CSS 样式。

      要更改刻度,您必须在 CSS 中指定 text(或使用类或 ID)。

      【讨论】:

      • 谢谢,但这并不能解决我的问题。轴标题“颜色”也是一个 SVG 文本,但它受 body CSS 选择器的影响。
      • 是的,你完全正确。浏览源代码总是一个好习惯!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      • 2012-07-24
      • 2013-07-06
      • 2017-03-16
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多