【问题标题】:Dynamic CSS selection within a group, SVG, Path组内的动态 CSS 选择、SVG、路径
【发布时间】:2014-11-12 02:02:44
【问题描述】:

我正在学习 CSS 并解决一个涉及路径动态颜色选择的问题。

我有一个SVG,它可以有任意数量的路径 (1+),并且有预定义的颜色,应该根据它们的顺序分配给路径。 (Web 服务返回一组路径)。

为简单起见,假设我有 4 条已知路径,并且可能有两种颜色:绿色和深粉色。

问题:如何动态分配以下颜色(无需为每个路径创建单独的类):

  • 路径 1:绿色
  • 路径 2:深粉色
  • 路径 3:绿色
  • 路径 4:深粉色

.path_group {
  stroke="black";
  fill="none";
  stroke-width="2";
}

.myPath{
  stroke:deepPink;
  stroke-width:1.3;
}

/*
Color1: Green
Color2: deepPink
*/
<svg width="100%" height="100%" viewBox="0 0 260 200"
     xmlns="http://www.w3.org/2000/svg">
  <g class="path_group" >
    <path class="myPath" d="M10,25 L110,10" />
    <path class="myPath" d="M10,35 L110,20" />
    <path class="myPath" d="M10,45 L110,30" />
    <path class="myPath" d="M10,55 L110,40" />
  </g>
</svg>

我更感兴趣的是在本地使用 CSS/JS,而不是在我的项目中添加任何框架或库。欢迎提出有关任何特定概念的建议。

演示Codepen

当前方法

this.colors = ["green", "deepPink"];

this.getColor = function (pathIndex) {
    return this.colors[pathIndex % this.colors.length];
};

【问题讨论】:

  • 通常动态 CSS 不是一个好主意(至少有人告诉我)
  • 你会为每个类添加类,除非特别是当你重复颜色时,否则你可以使用颜色范围,就像你绘制图表时那样。
  • 我添加了一个代码示例。目前,每当我创建一个新的 SVG 时,我都会使用路径索引调用 getColor 方法,并将返回的颜色设置为 svg 中的硬编码值

标签: javascript html css svg path


【解决方案1】:

您可以像这样使用 CSS3 :nth-child() 选择器 (w3schools):

.myPath { stroke-width:1.3; }

.path_group .myPath:nth-child(4n+1)
{ stroke:red; }
.path_group .myPath:nth-child(4n+2)
{ stroke:blue; }
.path_group .myPath:nth-child(4n+3)
{ stroke:green; }
.path_group .myPath:nth-child(4n+4)
{ stroke:deepPink; }

查看更新的 codepen here

【讨论】:

    猜你喜欢
    • 2016-02-18
    • 2021-08-23
    • 2019-10-18
    • 2019-06-08
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    相关资源
    最近更新 更多