我想在不同的 DIV 上使用相同的 SVG。但是,我希望 SVG 統一縮放到 div。
CodeSandbox 鏈接到我所擁有的作業示例如下

我想要什么

我如何實作這一目標?請告訴我。
uj5u.com熱心網友回復:
您將需要洗掉 svg 元素的寬度和高度屬性,計算每個容器的高度并將 svg 的寬度設定為等于容器的高度。這是有效的,因為圖示是方形的(參見 viewBox="0 0 500 500")
//all containers
let cc = document.querySelectorAll(".container");
cc.forEach((c) => {
//get the height of each container
let height = c.getBoundingClientRect().height;
//get the svg element inside each conteiner
let svg = c.querySelector("svg");
//set the width of the svg element
svg.style.width = height;
});
body {
margin: 0.15rem;
padding: 0.15rem;
}
.App {
font-family: sans-serif;
text-align: center;
}
.container {
display: flex;
align-items: center;
border: 1px solid brown;
border-radius: 0.25rem;
margin: 0.15rem;
padding: 0.15rem;
}
.Text {
display: inline-block;
margin: 0.15rem;
padding: 0.15rem;
}
<div class="App">
<div class="container">
<div><svg xmlns="http://www.w3.org/2000/svg" class="Icon" viewBox="0 0 500 500">
<path fill="none" id="mg" stroke="#000" stroke-width="36" stroke-linecap="round" d="m280,278a153,153 0 1,0-2,2l170,170m-91-117 110,110-26,26-110-110"></path>
</svg></div>
<h2 class="Text">Start editing to see some magic happen!</h2>
</div>
<div class="container">
<div><svg xmlns="http://www.w3.org/2000/svg" class="Icon" viewBox="0 0 500 500">
<use href="#mg"/>
</svg></div>
<h2 class="Text">Start editing to see some magic happen! if the magic does not happen, keep editing</h2>
</div>
<div class="container">
<div><svg xmlns="http://www.w3.org/2000/svg" class="Icon" viewBox="0 0 500 500">
<use href="#mg"/>
</svg></div>
<h2 class="Text">Start editing to see some magic happen! if the magic does not happen, keep editing. Even after typing nothing happens, you need to just give u ;-)</h2>
</div>
</div>
觀察:由于您使用的是相同的圖示,而不是重復放大鏡的代碼,您可以給路徑一個 id (id="mg") 并重用它<use>
uj5u.com熱心網友回復:
您可以將 SVG 保存在 .svg 檔案中并使用 img 元素來參考該標簽(例如 src="icon.svg"),這將為縮放 SVG 提供更大的靈活性
有關更多詳細資訊,請參閱:如何縮放 SVG
注意:我認為如果將圖示頂部對齊而不是縮放圖示會更好看
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432799.html
上一篇:什么定義了Boost的svg_mapper縮放和轉換?
下一篇:如何向下svg元素?
