не получается сменить цвет svg с помощью js
const colors = ['#FF47CA','#FBA0E3','#D71868','#FF77FF']
function heartsRandom(){
for (let i = 0; i < miniheart.length; i++){
const randomColorIndex = Math.floor(Math.random() * colors.length);
miniheart[i].style.fill = colors[randomColorIndex]
}
}
<div class="miniheart"><img src="assets\Heart_corazón.svg"></div>
Я могу поменять фон блока в котором находится эта svg-шка, но не её цвет
Ответы (1 шт):
Автор решения: Evgeniy Ivanchikov
→ Ссылка
SVG должно быть вставлено разметкой, а не картинкой. Это обязательно. Плюс для атрибутов fill/strocke, смотря что тебе нужно перекрашивать, укажи currentColor. Это тоже обязательно для JS скрипта.
const colors = ['#FF47CA','#FBA0E3','#D71868','#FF77FF']
const icon = document.querySelector('#icon')
function heartsRandom(){
const randomColorIndex = Math.floor(Math.random() * colors.length);
icon.style.color = colors[randomColorIndex];
}
heartsRandom();
<svg id="icon" xmlns="http://www.w3.org/2000/svg" width="800px" height="800px" viewBox="0 0 16 16" fill="none">
<path d="M1.24264 8.24264L8 15L14.7574 8.24264C15.553 7.44699 16 6.36786 16 5.24264V5.05234C16 2.8143 14.1857 1 11.9477 1C10.7166 1 9.55233 1.55959 8.78331 2.52086L8 3.5L7.21669 2.52086C6.44767 1.55959 5.28338 1 4.05234 1C1.8143 1 0 2.8143 0 5.05234V5.24264C0 6.36786 0.44699 7.44699 1.24264 8.24264Z" fill="currentColor"/>
</svg>