그 위에 두 개의 작은 이미지 / 버튼이있는 이미지가 있습니다. 각 이미지 / 버튼은 기본 이미지를 원본 이미지 또는 대체 이미지로 변경해야합니다. 작동하도록 작은 자바 스크립트 기능이 있습니다. 그러나 문제는 동일한 페이지에서 동일한 기능을 가진 2 개 이상의 이미지를 원할 때 발생합니다. 버튼은 모든 이미지를 한 번에 변경합니다. JS가 버튼이 눌린 DIV 내에서 이미지 만 변경하도록하는 간단한 솔루션이 있습니까?
HTML :
<div class="mobile-product-image-switcher">
<img src="main-image.jpg" alt="" class="mobile-product-switcher-image" />
<img src="switcher-button-1.jpg" alt="" class="switcher-button-1" onclick="changeImg('main-image.jpg')" />
<img src="switcher-button-2.jpg" alt="" class="switcher-button-2" onclick="changeImg('main-image-2.jpg')" />
</div>
<div class="mobile-product-image-switcher">
<img src="main-image-3.jpg" alt="" class="mobile-product-switcher-image" />
<img src="switcher-button-1.jpg" alt="" class="switcher-button-1" onclick="changeImg('main-image-3.jpg')" />
<img src="switcher-button-2.jpg" alt="" class="switcher-button-2" onclick="changeImg('main-image-4.jpg')" />
</div>
CSS :
.mobile-product-image-switcher {
position: relative;
top: 0;
left: 0;
width: 200px;
height: 200px;
z-index: 1;
}
.mobile-product-switcher-image {
position: relative;
top: 0;
left: 0;
}
.switcher-button-1 {
position: absolute;
bottom: 10px;
right: 50px;
width: 30px;
height: 30px;
z-index: 2;
background-color: white;
border-radius: 30px;
padding: 5px;
cursor: pointer;
}
.switcher-button-2 {
position: absolute;
bottom: 10px;
right: 15px;
width: 30px;
height: 30px;
z-index: 2;
background-color: white;
border-radius: 30px;
padding: 5px;
cursor: pointer;
}
JS :
function changeImg(src){
$('.mobile-product-image-switcher img.mobile-product-switcher-image').attr('src', src);}
감사합니다
Travis J가 귀하의 질문에 대해 언급 한 것에 대한 작은 예를 만들었습니다.
function changeImage(src, context) {
context.parentElement.querySelector(".image")
.setAttribute("src", "https://dummyimage.com/150/fefefe/888&text=" + src);
}
<div>
<img class="image" src="https://dummyimage.com/150/fefefe/888&text=1">
<img src="https://dummyimage.com/80/fefefe/888&text=1" onclick="changeImage('1', this)">
<img src="https://dummyimage.com/80/fefefe/888&text=2" onclick="changeImage('2', this)">
<div>
<div>
<img class="image" src="https://dummyimage.com/150/fefefe/888&text=3">
<img src="https://dummyimage.com/80/fefefe/888&text=3" onclick="changeImage('3', this)">
<img src="https://dummyimage.com/80/fefefe/888&text=4" onclick="changeImage('4', this)">
<div>
편집 :이 예제에서 jQuery를 사용하지 않고 src에 접두사를 추가하기 때문에 몇 가지 변경을 수행해야 할 수 있습니다 (예제에만 해당).
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다