今天,我遇到了一些问题,使用onclick
方法用js更改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>
发布于 2022-01-03 03:38:10
使用document.getElementById("arrow")
,您正在搜索<svg>
元素。
然后您将更改它的fill
属性,但是<path />
元素的fill
属性会覆盖它。因此,您必须将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>
发布于 2022-01-03 03:39:20
我建议使用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://stackoverflow.com/questions/70565125
复制相似问题