今天我在使用 js 的onclick方法更改 svg 的屬性時遇到了一些問題;
這是我想要做的:

這是我所做的:

(有箭頭,但灰色覆寫它)
這是我的代碼:
function social() {
document.getElementById("svg1").style.backgroundColor = "grey";
document.getElementById("arrow").setAttribute("fill", "#ff00ff")
}
<div id="svg1">
<svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13">
<path fill="#6E8098"
d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
</svg>
</div>
uj5u.com熱心網友回復:
與document.getElementById("arrow")您一起搜索<svg>元素。
然后你正在改變它的fill屬性,但是元素的fill屬性 <path />覆寫了它。所以,你必須上移id="arrow"來自<svg>于path移動fill從<path />到<svg>
function social() {
document.getElementById("svg1").style.backgroundColor = "grey";
document.getElementById("arrow").setAttribute("fill", "#ff00ff")
}
<div id="svg1">
<svg onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13">
<path id="arrow" fill="#6E8098"
d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
</svg>
</div>
或者
function social() {
document.getElementById("svg1").style.backgroundColor = "grey";
document.getElementById("arrow").setAttribute("fill", "#ff00ff")
}
<div id="svg1">
<svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13" fill="#6E8098">
<path
d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
</svg>
</div>
uj5u.com熱心網友回復:
我建議使用 CSS 類,然后使用classlist.toggle它在點擊時移動它:
function social() {
document.getElementById("arrow").classList.toggle('active');
}
.active {
background: grey;
border-radius: 30px;
padding: 10px;
}
.active > path {
fill: white;
}
<div id="svg1">
<svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13">
<path id='path' fill="#6E8098"
d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
</svg>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/402334.html
標籤:
上一篇:如何獲取雙向物體
下一篇:如何在SVG中繪制帶角的矩形
