css - D3通过CSS设置strike-dasharray

标签 css svg d3.js

在 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/

相关文章:

css - 制作具有不同开始、结束和中断的CSS菜单

javascript - D3.js 在线图上的一条线后面添加一个阴影时间范围区域

javascript - 在 WebViewer 中的 FileMaker for D3 中加载 JSON 文件

css - 如何在超宽网页上水平滚动居中?

css - 多个背景图片重复时可以交替吗?

javascript - 如何将CSS应用于没有类的div?

svg - 如何从旋转/平移/缩放值计算 SVG 变换矩阵?

javascript - SVG 符号 ViewBox 剪切圆形渲染,笔划=1

javascript - 未捕获的类型错误 : Cannot read property 'getTotalLength' of null

Javascript for 循环未捕获数据属性中的 TypeError