首页 > 解决方案 > SVG带文本和 div 填充宽度,带过渡

问题描述

我正在这里处理 SVG 我想要一个矩形来在 div 内添加文本并用过渡颜色填充我曾尝试过这样

<g>
  <rect width="25%" height="100%" fill="blue"></rect>
  <rect width="100%" height="100%" fill="none"></rect>
  <text x="0" y="50"  font-size="35" fill="green">text here</text>
</g>

仍然没有来,对于动画我试过这样

<animate attributeName="width" from="0" to="200" dur="5s" />

任何人都可以向我建议如何实现此输出。任何帮助将不胜感激

svg {
  width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="slider1" type="range" min="0" max="100" step="25" value="25" oninput="document.querySelector(`#SVG${this.id} rect`).setAttribute('width',this.value+'%')" />

<svg id="SVGslider1" viewBox="0 0 30 6">
  <rect width="25%" height="100%" fill="blue" />
  <rect width="100%" height="100%" fill="none" stroke="black"/>
</svg>

标签: javascripthtmlcsssvg

解决方案


尝试调整x,yfont-size在文本上添加一个transition属性rect

svg {
  width: 200px;
}

rect {
  transition: width 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="slider1" type="range" min="0" max="100" step="25" value="25" oninput="document.querySelector(`#SVG${this.id} rect`).setAttribute('width',this.value+'%')" />

<svg id="SVGslider1" viewBox="0 0 30 6">
  <rect width="25%" height="100%" fill="blue" />
  <rect width="100%" height="100%" fill="none" stroke="black"/>
  <text x="5" y="5"  font-size="6" fill="green">text here</text>
</svg>

编辑:要使元素垂直填充,请<rect>交换width和:heighty

svg {
  width: 200px;
}

rect {
  transition: y 0.5s, height 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="slider1" type="range" min="0" max="100" step="25" value="25" oninput="document.querySelector(`#SVG${this.id} rect`).setAttribute('height',this.value+'%');document.querySelector(`#SVG${this.id} rect`).setAttribute('y',100-this.value+'%')" />

<svg id="SVGslider1" viewBox="0 0 30 6">
  <rect y="75%" width="100%" height="25%" fill="blue" />
  <rect width="100%" height="100%" fill="none" stroke="black"/>
  <text x="5" y="5"  font-size="6" fill="green">text here</text>
</svg>


推荐阅读