본문 바로가기
코드 정리/Jquery

Jquery 예제 썸네일 이미지 클릭시 메인 이미지 교체 및 글 올라오기

by rien_d 2023. 4. 16.

 

 

작은 이미지를 클릭하면 큰 이미지가 교체되고 설명 글이 올라오는 예제

 

기본 구조

<div id="largeImg">
  <img scr="./img/largeimg1.jpg">
</div>

<div class="thumbs">
  <a href="./img/largeimg1.jpg"><img src="./img/small1.jpg>"</a>
  <em>글설명</em>
  <a href="./img/largeimg2.jpg"><img src="./img/small2.jpg>"</a>
  <em>글설명</em>
  <a href="./img/largeimg3.jpg"><img src="./img/small3.jpg>"</a>
  <em>글설명</em>
</div>

 

&('em').hide()
// 먼저 작성되어 있는 글 숨김

$('thumbs a').click(function(){
  $('#caption').remove()
  $('#largeImg img').attr('src', $(this).attr('href'))
  // 작은 이미지를 클릭하면 큰이미지의 src 속성을 지금 선택한 요소의 href값으로 변경
  // #caption은 뒤에서 만들어지는 요소
  
  const msg = $(this).next('em').text()
  $('#largeImg').append("<div id='caption'></div>")
  $('#largeImg #caption').text(msg)
  // 변수 msg에 지금 클릭한 a의 다음 em요소의 텍스트를 담아 놓고
  // #largeImg의 밑에 #caption요소를 생성하고 msg를 뿌려 줌.
  
  const posy = $('#caption').height()+25
  $('#caption').animate({
    top: "-"+posy+"px"
  },500)
  //#caption 요소에 애니메이션 효과를 넣어 top에서 마이너스 값으로 요소 크기만큼 올라가는 효과를 줌
  
  return false
  // a의 기본 속성 막기
})