Tengo una línea vertical SVG dentro de mi barra de navegación y quiero cambiar su color de trazo al desplazarme usando la manipulación DOM.
Puedo cambiar el color de fondo de mi barra de navegación al desplazarme y también el ancho de la línea SVG usando la manipulación DOM, pero no puedo cambiar el color del trazo. He usado muchos métodos, pero nadie está funcionando.
Ayúdenme con lo mismo. Estoy proporcionando mi código SVG y código JavaScript también.
Mi código de imagen 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>Mi código 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); } }Intenta seleccionar con querySelector("svg > line") :
window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) { document.querySelector("svg > line").setAttribute("stroke","red") } else { document.querySelector("svg > line").setAttribute("stroke","white") } } <p>↓</p> <p>↓</p> <p>↓</p> <p>↓</p> <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> <p>↑</p> <p>↑</p> <p>↑</p> <p>↑</p> <p>↑</p> <p>↑</p> <p>↑</p> <p>↑</p> <p>↑</p> <p>↑</p>Alternativa y más fácil cuando desea cambiar múltiples selectores y propiedades de CSS,
es alternar el estado disabled de una etiqueta <style id="scrolled"> completa
Con algo de lógica adicional, incluso podría administrar múltiples scrollTop, por ejemplo. scrolled_over_50 posiciones recorriendo todos los elementos document.querySelectorAll('style[id^="scrolled"]') .
window.onscroll = function() { document.querySelector("#scrolled") .disabled = !document.documentElement.scrollTop } <style> * { height:35vh } p { background:pink } #svg1 rect { fill:blue } </style> <style id="scrolled" onload="this.disabled=true"> #svg1 { background:green } #svg1 rect { fill:lightgreen } </style> <p></p> <svg id="svg1" viewBox="0 0 100 50" > <rect x="10%" y="10%" width="80%" height="80%"/> </svg> <p></p>