2017-11-16 35 views
0

동일한 이미지가 2 세트 있습니다. 1은 갤러리입니다 another 표시되는 이미지 목록 : 없음; 해당 이미지가 클릭 될 때까지 (기본적으로 라이트 박스)요소를 클릭하고 다른 노드 목록의 동일한 색인을 가진 다른 요소에 요소를 추가하는 클래스

예 : 나는 갤러리에서 이미지를 통해 루프 및 각 IMG에 더 리스너를 추가 한

<ul id="gallery"> 
    <li><img class="gallery-image" src="dog"></li> 
    <li><img class="gallery-image" src="cat"></li> 
    <li><img class="gallery-image" src="rabbit"></li> 
</ul> 

<ul id="modal"> 
    <li><img class="modal-image" src="dog"></li> 
    <li><img class="modal-image" src="cat"></li> 
    <li><img class="modal-image" src="rabbit"></li> 
</ul> 

.

이러한 이미지는 두 목록에서 동일한 순서로 있으며 document.getElementsByClassName을 사용할 때 동일한 색인을 가지며 노드 목록을 반환합니다. (galleryImage [0]과 modalImage [0] 같은 다른 변수 이름을 가지고 있습니다.) 노드 목록을 사용하여 "gallery-image"를 클릭하면 해당 "모달 이미지"에 클래스를 추가 할 수 있습니까? 기본적으로 galleryImage [0]이 닫히면 modalImage [0]에 클래스를 추가하려고합니다.

이렇게하는 방법이 있습니까? 취할 접근법은 무엇입니까?

예제를 찾았으며 "답변"을 받았지만 각 이미지에 색인 번호가있는 ID를 할당하고 모든 파일을 1 개의 파일로 유지하고 정리가 잘되어있는 방법을 배우는 것이 좋습니다. nodelists와 놀아 라. 사람이 오히려 "대답"

미리

답변

1

에 감사보다 뒤에 논리를 이해하기 위해 자신의 답을 설명 할 수있는 경우에도

감사하겠습니다 질문이 아래로 비등 나에게 보인다 "을 감안할 때 DOM 요소에 대한 참조, NodeList에서 색인을 어떻게 확인할 수 있습니까? " 다른 요소에서 해당 요소를 가져 오는 두 번째 부분은 일단 색인이 있으면 간단합니다.

그래서 당신은 배열 내에서 항목의 인덱스를 찾기 위해 array .indexOf() method를 사용하거나 .call()를 통해 당신은 NodeList를에이 방법을 사용할 수 있습니다 후 index 인덱스 것입니다 ...

var index = Array.prototype.indexOf.call(galleryImages, elementToFind) 

당신이 찾고있는 요소의 (또는 발견되지 않았 으면 -1이 표시되지만, 귀하의 경우에는 발견 될 것입니다.) 그러면 modalImages[index]은 다른 목록의 해당 항목입니다.

또한 루프에있는 모든 이미지에 클릭 핸들러를 바인딩하는 대신 하나의 핸들러를 포함하는 UL 요소에 바인딩하고 해당 핸들러 내에서 event.target을 테스트하여 IMG 요소였습니다. 이를 위임 된 이벤트 처리라고합니다. 요소의 클릭 이벤트가 포함 된 요소를 통해 거품을 일으키므로 갤러리 IMG 요소 중 하나를 클릭하면 UL 수준에서 처리 할 수 ​​있습니다.

데모 용으로 클릭 할 때 클래스에 해당 항목을 노란색으로 지정하고 이전 선택을 제거합니다.

// Get references to the UL elements: 
 
var galleryContainer = document.getElementById("gallery") 
 
var modalContainer = document.getElementById("modal") 
 

 
// Get the lists of IMG elements: 
 
var galleryImages = galleryContainer.querySelectorAll(".gallery-image") 
 
var modalImages = modalContainer.querySelectorAll(".modal-image") 
 

 
// Bind click handler to gallery UL: 
 
galleryContainer.addEventListener("click", function(event) { 
 
    // If the target of the click wasn't an element we care about just return immediately 
 
    if (event.target.tagName.toLowerCase() != "img") 
 
    return 
 
    
 
    // Check for a current .selected element, and if it exists remove the class from it 
 
    var currentSelected = document.querySelector(".selected") 
 
    if (currentSelected) 
 
    currentSelected.classList.remove("selected") 
 
    
 
    // Find the index of the current IMG in the list, and use that index 
 
    // to get the corresponding item in the other list 
 
    var index = Array.prototype.indexOf.call(galleryImages, event.target) 
 
    modalImages[index].classList.add("selected") 
 
});
.selected { background-color: yellow; }
<ul id="gallery"> 
 
    <li><img class="gallery-image" src="dog" alt="dog"></li> 
 
    <li><img class="gallery-image" src="cat" alt="cat"></li> 
 
    <li><img class="gallery-image" src="rabbit" alt="rabbit"></li> 
 
</ul> 
 
<ul id="modal"> 
 
    <li><img class="modal-image" src="dog" alt="dog"></li> 
 
    <li><img class="modal-image" src="cat" alt="cat"></li> 
 
    <li><img class="modal-image" src="rabbit" alt="rabbit"></li> 
 
</ul>