Как подсветить квадрат из группы?
Имеется навигация которая имеет ссылку в виде href="здесь id группы" и так же имеются <g> внутри которых лежат два rect .
Верхний rect видно так как его стили записаны в теге, а нижний нет так как он стилизован в css и имеет fill: transparent;
Как сделать что бы при прохождении курсора над ссылкой подсветить нужный прозрачный rect другими словами подменить на fill: yellow;?
Мой код:
let nav = document.querySelectorAll("a");
let rect = document.querySelectorAll("rect");
let g = document.querySelectorAll("g");
console.log(g)
for (var i = 0; i < nav.length; i++) {
nav[i].mousemove = function(e) {
e.preventDefault();
let event = e.target;
console.log(event)
}
}
html,
body {
margin: 0;
padding: 0;
}
g rect:nth-child(2) {
fill: yellow;
opacity: 0;
}
a {
font-size: 24px;
display: block;
margin: 6px;
}
.svg {
width: 600px;
}
<a href="#r1">section a</a>
<a href="#r2">section b</a>
<a href="#r3">section c</a>
<a href="#r4">section d</a>
<div class="svg">
<svg viewBox="0 0 600 460">
<g id="r1">
<rect x="100" y="100" width="50" height="30" fill="#00f" />
<rect x="100" y="100" width="50" height="30" />
</g>
<g id="r2">
<rect x="200" y="200" width="30" height="20" fill="#ccc" />
<rect x="200" y="200" width="30" height="20" />
</g>
<g id="r3">
<rect x="300" y="300" width="40" height="50" fill="#f00" />
<rect x="300" y="300" width="40" height="50" />
</g>
<g id="r4">
<rect x="400" y="400" width="40" height="40" fill="#0ff" />
<rect x="400" y="400" width="40" height="40" />
</g>
</svg>
</div>
Ответы (1 шт):
Автор решения: OPTIMUS PRIME
→ Ссылка
let nav = document.querySelectorAll("a");
for (let i = 0; i < nav.length; i++) {
nav[i].addEventListener('mouseenter', function() {
toggleRect(i, 1);
});
nav[i].addEventListener('mouseleave', function() {
toggleRect(i, 0);
});
}
function toggleRect(i, opacity) {
let rect = document.querySelectorAll('div.svg g rect:nth-child(2)')[i];
// let rect = document.querySelectorAll('div.svg g')[i].children[1];
// let rect = document.getElementById('r' + (i + 1)).children[1];
rect.style.opacity = opacity;
}
g rect:nth-child(2) {
fill: yellow;
opacity: 0;
}
a {
font-size: 24px;
display: block;
margin: 6px;
}
.svg {
width: 600px;
}
<a href="#a">section a</a>
<a href="#b">section b</a>
<a href="#c">section c</a>
<a href="#c">section d</a>
<div class="svg">
<svg viewBox="0 0 600 460">
<g id="r1">
<rect x="10" y="0" width="10" height="10" fill="#00f" />
<rect x="10" y="0" width="10" height="10" />
</g>
<g id="r2">
<rect x="50" y="10" width="20" height="20" fill="#ccc" />
<rect x="50" y="10" width="20" height="20" />
</g>
<g id="r3">
<rect x="90" y="20" width="30" height="30" fill="#f00" />
<rect x="90" y="20" width="30" height="30" />
</g>
<g id="r4">
<rect x="130" y="40" width="40" height="40" fill="#0ff" />
<rect x="130" y="40" width="40" height="40" />
</g>
</svg>
</div>