【问题标题】:D3 setting stroke-dasharray through CSSD3通过CSS设置stroke-dasharray
【发布时间】:2016-11-22 21:34:49
【问题描述】:

在 D3 v4 中,我发现将 stroke-dasharray 指定为属性可以按预期工作。另一方面,通过样式指定它不会。请参阅本说明末尾的代码清单。

根据 Mozilla 基金会 (https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes):

“使用 CSS

除了设置对象的属性外,您还可以使用 CSS 来设置填充和描边的样式。并非所有属性都可以通过 CSS 设置。处理绘画和填充的属性一般都有,所以fill、stroke、stroke-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 svg d3.js


    【解决方案1】:

    您在 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) 我没有在下面提供的示例代码中正确实现样式。

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 2017-08-01
      • 2019-09-26
      • 1970-01-01
      • 2021-01-01
      • 2021-08-08
      • 2018-05-12
      • 2019-08-18
      • 2019-09-09
      相关资源
      最近更新 更多