首页 > 解决方案 > 嵌套时如何修改CSS值?

问题描述

我可以更改 percent1 的顶部属性

document.getElementById('percent1').style.top = '50px';

HTML:

<div class="box" id="box1">
  <div class="percent" id="percent1">
   <svg>
      <circle cx="70" cy="70" r="70"></circle>
      <circle cx="70" cy="70" r="70"></circle>
    </svg>
    <div class="num">
      <h2>45<span>%</span></h2>
    </div>
  </div>
  <h2 class="text">Percentage</h2>
</div>

要修改的 CSS:

.box .percent svg circle:nth-child(2)
{
  stroke-dashoffset:calc(440 - (440 * 15) / 100);
}

像这样嵌套时如何更改“stroke-dashoffset”值?

标签: javascriptcss

解决方案


看起来:nth-child 定位匹配元素是基于它们的位置,而不是它们的属性,所以我认为这种方法不可能实现你想要的。

可以考虑附加一些其他类型的定位机制(在 HTML 或 JS 中)来定位您想要在 CSS 中更精细地设置样式的元素。

#percent1 {
  position: absolute;
  top: 50px;
}

#percent1>svg {
  overflow: visible;
}

#percent1>svg>circle {
  fill: blue;
}

#percent1>svg>circle:nth-child(2) {
  fill: yellow;
}

#circle-target {
  stroke-dashoffset: 100;
  stroke: red;
  stroke-width: 8px;
}
<div class="box" id="box1">
  <div class="percent" id="percent1">
    <svg>
      <circle cx="70" cy="70" r="70"></circle>
      <circle cx="70" cy="70" r="70" id="circle-target"></circle>
    </svg>
  </div>


推荐阅读