[JQuery] 간단한 슬라이더 구현 코드

2022. 8. 23.공부/JavaScript

728x90

HTML

<div class="main-slider">
     <a href="#"><img src="images/slide/slide1.png" alt="슬라이드이미지1" id="slide-image"></a>
     <a href="#"><img src="images/slide/slide2.png" alt="슬라이드이미지2" id="slide-image"></a>
     <a href="#"><img src="images/slide/slide3.png" alt="슬라이드이미지3" id="slide-image"></a>
</div>

 

CSS

.main-slider {
    position: absolute;
    top:100px;
    height: 300px;
    width: 1200px;
    overflow: hidden;
}

.main-slider > a {
    position:absolute;
    top:0;
    left:0;
    overflow: hidden; 
}

.main-slider img {
    width: 100%;
    height: 100%;
}

 

JS

window.onload  = function(){
    console.log("연결확인");
    start();
}


var imgs = 2;
var now = 0;

function start(){
  $(".main-slider>a").eq(0).siblings().animate({width:"-1200px"});

  setInterval(function(){
    now = now == imgs ? 0 : now+=1;
    $(".main-slider>a").eq(now-1).animate({width:"-1200px"});
    $(".main-slider>a").eq(now).animate({width:"1200px"});
  },3000)}