【发布时间】:2021-09-05 12:12:22
【问题描述】:
我的导航栏中有一条垂直线 SVG,我想在滚动时使用 DOM 操作更改其笔触颜色。
我可以在滚动时更改导航栏的背景颜色,也可以使用 DOM 操作更改 SVG 线的宽度,但无法更改笔触颜色我使用了很多方法,但没有人在工作。
请帮助我提供我的 SVG 代码和 JavaScript 代码。
我的 SVG 图像代码:-
<svg id="svg" width="4" height="71" viewBox="0 0 4 71" fill="none" xmlns="http://www.w3.org/2000/svg">
<line x1="2.49985" y1="0.0214264" x2="1.49985" y2="70.0214" stroke="#FF0A0A" stroke-width="8"/>
</svg>
我的 JAVASCRIPT 代码:-
useEffect(() => {
window.onscroll = function() {scrollFunction()};
})
function scrollFunction() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
// document.getElementById("header").style.background = "red";
// document.getElementById("header").style.transition = "0.70s";
// document.getElementById("logotext").style.color = "white";
// document.getElementById("svg").stroke="red"
// document.getElementById("svg").style.stroke="red"
document.getElementById("svg").setAttribute("stroke","red")
console.log( document.getElementById("svg").stroke);
} else {
document.getElementById("header").style.background = "";
document.getElementById("svg").setAttribute("stroke","white")
console.log( document.getElementById("svg").stroke);
}
}
【问题讨论】:
-
代替
document.getElementById("svg").setAttribute("stroke","red")尝试设置线条document.querySelector("line").setAttribute("stroke","red")的笔触属性 -
非常感谢这解决了我的问题
标签: javascript html css svg