при клику к блоку приминяется стиль js
let table = document.getElementById('tableS');
let selectedTd;
table.onclick = function (event) {
let target = event.target;
while (target != this) {
if (target.tagName == 'img') {
highlight(target);
return;
}
target = target.parentNode;
}
}
function highlight(node) {
if (selectedTd) {
selectedTd.classList.remove('highlight');
}
selectedTd = node;
selectedTd.classList.add('highlight');
}
#tableS th {
text-align: center;
font-weight: bold;
}
#tableS td {
width: 150px;
white-space: nowrap;
text-align: center;
vertical-align: bottom;
padding-top: 5px;
padding-bottom: 12px;
}
#tableS .highlight {
opacity: 1;
}
h1, p{
text-align:center;
}
img.animate {
opacity: 0.25;
}
img.animate:hover {
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>task6</title>
<link rel="stylesheet" href="task1.css">
</head>
<body>
<table id="tableS">
<tr>
<td class="n">
<img class="animate" src="https://i.ytimg.com/vi/afYv49pALJk/hqdefault.jpg" height="300px" width="300px"> </td>
</td>
<td class="n">
<img class="animate" src="https://i.ytimg.com/vi/afYv49pALJk/hqdefault.jpg" height="300px" width="300px"> </td>
</td>
<td class="n">
<img class="animate" src="https://i.ytimg.com/vi/afYv49pALJk/hqdefault.jpg" height="300px" width="300px"> </td>
</tr>
</table>
<script src="task1.js"></script>
</body>
</html>
Как реализовать через js,что бы при клику по картинка пропадал фон(серый), снова при клику появлялся
Ответы (1 шт):
Автор решения: OPTIMUS PRIME
→ Ссылка
Ваш код не срабатывает только из-за того, что сравниваете if (target.tagName == 'img') — tagName всегда пишется большими буквами) Заменить на == "IMG" и заработает.
Но вообще-то while (target != this) тоже не нужен в этом случае: Внутри img не бывает других элементов. Если на что-то кликнули, то это или img или нет, без вариантов.
let table = document.getElementById("tableS");
table.addEventListener("click", function(e) {
if (e.target.tagName == "IMG") {
e.target.classList.toggle("active");
}
});
img.animate {
width: 150px;
height: 150px;
opacity: 0.25;
}
img.animate.active {
opacity: 1;
}
<table id="tableS">
<tr>
<td class="n">
<img class="animate" src="https://i.ytimg.com/vi/afYv49pALJk/hqdefault.jpg">
</td>
<td class="n">
<img class="animate" src="https://i.ytimg.com/vi/afYv49pALJk/hqdefault.jpg">
</td>
<td class="n">
<img class="animate" src="https://i.ytimg.com/vi/afYv49pALJk/hqdefault.jpg">
</td>
</tr>
</table>