Javascript [ 버튼에 따른 사진 변경 ( Slide ) ]

양혜정·2024년 4월 13일
0

javascript_web

목록 보기
30/81

버튼에 따른 사진 변경

  • 사진 숨겼다 보여주기
  • 옆으로 이동하는 효과 없이 사진 변경( 숨겼다 보여주기 )

기본 설정

  • HTML
    -> div 1 개로 진행

  • CSS
    -> div width,height 와 img의 width,height 동일하게 설정
    -> overflow 를 설정 X
    -> img 의 transition X

  • JS
    -> div의 위치값 사용 X


초기 설정

  • 버튼위치 잡기
const 버튼이름1 = document.querySelector("버튼위치1");
const 버튼이름2 = document.querySelector("버튼위치2");
const images = document.querySelectorAll("div > img");
  • 초기 설정 ( 이미지 보이지 않게 하기 )
images.forEach(elmt => {elmt.style.display = "none";});
  • 초기 설정 ( 첫번째 이미지만 보이게 하기 )
images[0].style.display = "";

함수 선언

  • 버튼 클릭 시 함수 호출
버튼이름.addEventListener('click', 함수명);

함수 내

  • 초기설정 ( 모든 이미지 보이지 않게 하기 )
images.forEach(elmt => {elmt.style.display = "none";});
  • 다음 이미지 보이게 하기
const img = images[++current_index];
img.style.display = "";
  • 이전 이미지 보이게 하기
const img = images[--current_index];
img.style.display = "";

이미지 효과 주기

  • 광도
img.style.opacity = "숫자";		// 광도 : 0 ~ 1
  • 서서히 보이게 하기, 서서히 감추기
    increase 와 del 설정 후 setInterval 적용
let increase = 0;
// let del = 0;   // 감소값     
const 함수명 = setInterval(function(){
	increase += 0.005;
    // del += 0.005;           
    img.style.opacity = `${Number(opc) + increase}`;
    // img.style.opacity = `${Number(opc) - del}`;  
   	// 주의 opc 는 string 타입!!
    if(Number(img.style.opacity) == "1.0"){
    // if(Number(img.style.opacity) == "0.3"){  
    clearInterval(함수명);
 	}
},10);	// 10은 밀리초

참고

slide : https://velog.io/@jjoung-2j/Javascript-Slide


정리

  • 10_slide
    -> slide_hide_show.js, slide_hide_show.css, slide_hide_show.js

0개의 댓글

관련 채용 정보