我一直在审查 articles like this one这真的很好,但可能已经过时了,我想知道在保持纵横比的同时使内联 svg 具有响应性的简单方法是否取得了任何进展?
换句话说,如果我们在 div 容器中有一个长宽比为 1:1 的 svg,并且容器从 400x400px 缩小到 200x200px,那么 View 框的宽度和高度参数就会加倍。
最佳答案
我对你想要的东西感到困惑。我不知道你的意思,在你的问题中,当你谈论“ View 框宽度和高度参数双倍”时。也许您对 viewBox
的工作原理感到困惑。
只要 SVG 有一个 viewBox
,它就应该是响应式的。
在下面的示例中,我将 SVG 放入 div
容器中,并对容器大小进行动画处理以模拟页面大小的变化。
#container {
width: 200px;
background: linen;
animation: scale 1s alternate infinite;
}
@keyframes scale {
from { width: 200px; }
to { width: 100px; }
}
<div id="container">
<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="gold"/>
<rect x="10" y="50" width="20" height="50" fill="gold"/>
<rect x="70" y="50" width="20" height="50" fill="gold"/>
<circle cx="35" cy="45" r="5"/>
<circle cx="65" cy="45" r="5"/>
</svg>
</div>
但它也可以很容易地成为一个页面宽度的容器。尝试运行以下代码段。然后单击“全页”并调整浏览器窗口的大小。:
#container {
width: 100%;
background: linen;
}
<div id="container">
<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="gold"/>
<rect x="10" y="50" width="20" height="50" fill="gold"/>
<rect x="70" y="50" width="20" height="50" fill="gold"/>
<circle cx="35" cy="45" r="5"/>
<circle cx="65" cy="45" r="5"/>
</svg>
</div>
关于javascript - 在不使用 javascript 的情况下使内联 SVG 在浏览器中响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51528518/