尝试为图像选择器轮播创建功能
图像选择器的功能:
- 单击主图像下方容器中的图像
- 单击的 img 显示在主图像容器中
- 先前显示的主图像填充到主图像下方的容器中,以代替选定的图像
html
<div class="single-pro-images">
<div class="main-image" onclick="clicked();">
<img src="https://cdn.marvel.com/u/prod/marvel/i/mg/b/e0/56a7c0725bcbb/clean.jpg" width="100%" alt=""></div>
<div class="small-img-group">
<div class="small-img-col">
<img src="https://ids.si.edu/ids/deliveryService?max=800&id=https%3A%2F%2Famericanhistory.si.edu%2Fsites%2Fdefault%2Ffiles%2FAHB2008q04107.jpg" width="100%" class="small-img" alt="">
</div>
<div class="small-img-col">
<img src="https://i0.wp.com/blog.gocollect.com/wp-content/uploads/2022/02/75960620003000431.jpg?ssl=1" width="100%" class="small-img" alt="">
</div>
<div class="small-img-col">
<img src="https://cdn.marvel.com/content/1x/fcbdasmven2023_cover-resized.jpg" width="100%" class="small-img" alt="">
</div>
</div>
</div>
css
.single-pro-images {
width: 25%;
margin: 0px 15px 0px 0px;
}
.small-img-group {
display: flex;
justify-content: space-between;
margin-top: 15px;
}
.small-img-col {
flex-basis: 24%;
cursor: pointer;
}
通过尝试获取主图像 src 来启动代码,如果图像 src 不相等,则控制台日志显示 true 或 false,并且当 src 不相等时,主图像将更改。坚持编写 if 语句,因为我确定图像是否可以存储为值。
JS
let mainImg = document.getElementsByClassName("main-image");
function clicked() {
if (mainImg !== "https://cdn.marvel.com/u/prod/marvel/i/mg/b/e0/56a7c0725bcbb/clean.jpg"); {
console.log(true);
}
昨天学习了布尔/if 语句和函数,尝试应用今天的课程,但感觉像是本末倒置。
所以这是我的新 clicked 函数,其中 arg = newSrc 给出参数
function clicked(newSrc) {
// Select the main image ( we could use querySelector(".main-image") )
let mainImg = document.getElementsByClassName("main-image")[0];
// we use [0] to refer to the first elements in our dom obj here is the main img
// in case of querySelector it will return only one obj so we dont need indexing [0]
// use a temp variable to store the main image SRC
let tempSrc = mainImg.src;
// Set the main image src to the newSrc givin in the function argument
mainImg.src = newSrc;
// change the clicked image src to the main image src
// event.target to target the clicked element
event.target.querySelector(".small-img").src = tempSrc ;
}
您还需要像这样更改HTML 代码
<img class="main-image" src="1.jpg" width="100%" alt="" />
<div class="small-img-group">
<div class="small-img-col" onclick="clicked('2.jpg')"> <!-- on click funtion here -->
<img src="2.jpg" width="100%" class="small-img" alt="" />
</div>
<div class="small-img-col" onclick="clicked('3.jpg')"> <!-- on click funtion here -->
<img src="3.jpg" width="100%" class="small-img" alt="" />
</div>
<div class="small-img-col" onclick="clicked('4.jpg')"> <!-- on click funtion here -->
<img src="4.jpg" width="100%" class="small-img" alt="" />
</div>
</div>
您只需将 1.jpg 等更改为您的图像源