在 D3 v4 中,我发现将 stroke-dasharray 指定为属性可以按预期工作。另一方面,通过样式指定它则不然。请参阅本说明末尾的代码 list 。
根据 Mozilla 基金会 ( https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes ) 的说法:
“使用CSS
除了设置对象的属性之外,您还可以使用 CSS 来设置填充和描边的样式。并非所有属性都可以通过 CSS 设置。处理绘画和填充的属性通常都是可用的,因此 fill、strike、strike-dasharray 等...都可以这样设置..."
因此存在以下三种可能性之一:
1)我没有在下面提供的示例代码中正确实现样式。
2) D3 没有正确实现样式。
3) Mozilla 基金会关于能够通过 CSS 设置Stroke-dasharray 的说法是错误的。
是哪一个?
代码:
<!DOCTYPE html>
<html>
<head>
<script src='https://d3js.org/d3.v4.min.js'></script>
<style>
.dashed {
stroke-dasharray: '5,3';
}
</style>
</head>
<body>
<svg height=200 width=500></svg>
</body>
<script>
var svg = d3.select('svg');
svg.append('line')
.attr('x1', 0)
.attr('x2', 500)
.attr('y1', 25)
.attr('y2', 25)
.style('stroke', 'blue')
.style('stroke-width', '2px')
.style('stroke-dasharray', '5,3');
svg.append('line')
.attr('x1', 0)
.attr('x2', 500)
.attr('y1', 75)
.attr('y2', 75)
.style('stroke', 'blue')
.style('stroke-width', '2px')
.attr('class', 'dashed');
</script>
</html>
最佳答案
您在 CSS 中使用了字符串,这是无效的属性值。相反,它应该是一个数字:
.dashed {
stroke-dasharray: 5,3;
}
检查一下:
<html>
<head>
<script src='https://d3js.org/d3.v4.min.js'></script>
<style>
.dashed {
stroke-dasharray: 5,3;
}
</style>
</head>
<body>
<svg height=200 width=500></svg>
</body>
<script>
var svg = d3.select('svg');
svg.append('line')
.attr('x1', 0)
.attr('x2', 500)
.attr('y1', 25)
.attr('y2', 25)
.style('stroke', 'blue')
.style('stroke-width', '2px')
.style('stroke-dasharray', '5,3');
svg.append('line')
.attr('x1', 0)
.attr('x2', 500)
.attr('y1', 75)
.attr('y2', 75)
.style('stroke', 'blue')
.style('stroke-width', '2px')
.attr('class', 'dashed');
</script>
</html>
因此,正确答案是数字 1:
1) I am not implementing the style properly in the sample code provided below.
关于css - D3通过CSS设置strike-dasharray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40743077/