如何 - 单击图像时将不透明度设置为 1 并降低其他图像的不透明度
我一生都无法弄清楚这一点!我怎样才能做到这一点 - 单击图像时将不透明度设置为 1 并降低其他图像的不透明度?有人告诉我要向单击的图像添加一个类,存储它,然后在单击另一个图像时删除该类?但我不明白!
let items = document.getElementsByClassName("item");
document.body.addEventListener('click', (event) => {
const el = event.target;
for(var i=0; i< smallImg.length; i++) {
if (el.className !== 'sec') return;
const wasSelected = el.classList.contains('selected');
for (const d of document.querySelectorAll('div >img'))
d.classList.remove('selected');
el.classList.toggle('selected', !wasSelected)
console.log(".selected");
}
});
.sec:not(:first-child) {
opacity: 0.3;
}
.sec:not:active{
opacity: 0.3;
}
<div class="image-container">
<img
src="https://source.unsplash.com/400x400/?stationery"
class="item main-image"
/>
<div class="secondary-image">
<img
src="https://source.unsplash.com/100x100/?pen"
class="item sec item-1 active "
/>
<img
src="https://source.unsplash.com/100x100/?pencil"
class="item sec item-2"
/>
<img
src="https://source.unsplash.com/100x100/?notepad"
class="item sec item-3"
/>
<img
src="https://source.unsplash.com/100x100/?eraser"
class="item sec item-4"
/>
</div>
I couldn't for the life of me figure this out! How can I make this happen - When image is clicked set opacity to 1 and lower opacity for other images? I was told to add a class to the clicked image, store it, then remove the class when another image is clicked? but i cant figure it out!
let items = document.getElementsByClassName("item");
document.body.addEventListener('click', (event) => {
const el = event.target;
for(var i=0; i< smallImg.length; i++) {
if (el.className !== 'sec') return;
const wasSelected = el.classList.contains('selected');
for (const d of document.querySelectorAll('div >img'))
d.classList.remove('selected');
el.classList.toggle('selected', !wasSelected)
console.log(".selected");
}
});
.sec:not(:first-child) {
opacity: 0.3;
}
.sec:not:active{
opacity: 0.3;
}
<div class="image-container">
<img
src="https://source.unsplash.com/400x400/?stationery"
class="item main-image"
/>
<div class="secondary-image">
<img
src="https://source.unsplash.com/100x100/?pen"
class="item sec item-1 active "
/>
<img
src="https://source.unsplash.com/100x100/?pencil"
class="item sec item-2"
/>
<img
src="https://source.unsplash.com/100x100/?notepad"
class="item sec item-3"
/>
<img
src="https://source.unsplash.com/100x100/?eraser"
class="item sec item-4"
/>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

只需选择当前具有
active
类的元素,如果存在这样的元素,则从中删除该类。然后将其添加到单击的那个中。(当前不包括对单击的元素是否实际上是这些图像之一的任何检查。我只是保留
body
的常规单击处理程序,请自行改进以仅在需要时应用。)Just select the element that currently has the
active
class, and if such an element exists, remove that class from that. And then add it to the one that was clicked.(Any check on whether the clicked element was actually one of those images, is not currently included. I simply kept your general click handler for
body
, please refine this yourself to apply only where needed.)