检索d3轴路径的stroke-width属性

时间:2017-03-15 23:13:45

标签: javascript d3.js

在下面的脚本中,我可以检索d3轴路径的“stroke”属性,但我不能对“stroke-width”属性执行相同的操作(控制台打印为null)。有没有办法检索“笔画宽度”属性,以便我可以在下游使用它?

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

var x = d3.scaleLinear()
		  .domain([0, 10])
		  .range([margin, width - margin]);

// Add the Axis
svg.append("g")
   .attr("transform", "translate(0, " + (height/2) + ")")
   .attr("class", "xAxis")
 .call(d3.axisBottom(x)
   .tickValues([0, 10])
   );
   
   
console.log(d3.select(".xAxis path").attr("stroke"))
console.log(d3.select(".xAxis path").attr("stroke-width")) //this returns null
.xAxis path{
  stroke: black;
  stroke-width: 4px;
}

.xAxis text{
  fill: black;
  font-size: 14px;
}
<!doctype html>
<meta charset="utf-8">

<script src="https://d3js.org/d3.v4.min.js"></script>

<body></body>

1 个答案:

答案 0 :(得分:1)

由于您在CSS中设置了stroke-width,因此必须为style,而不是attr

console.log(d3.select(".xAxis path").style("stroke-width"))
//using style as a getter -------------^

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

var x = d3.scaleLinear()
		  .domain([0, 10])
		  .range([margin, width - margin]);

// Add the Axis
svg.append("g")
   .attr("transform", "translate(0, " + (height/2) + ")")
   .attr("class", "xAxis")
 .call(d3.axisBottom(x)
   .tickValues([0, 10])
   );
   
   
console.log(d3.select(".xAxis path").attr("stroke"))
console.log(d3.select(".xAxis path").style("stroke-width"))
.xAxis path{
  stroke: black;
  stroke-width: 4px;
}

.xAxis text{
  fill: black;
  font-size: 14px;
}
<!doctype html>
<meta charset="utf-8">

<script src="https://d3js.org/d3.v4.min.js"></script>

<body></body>