jquery slide div within a div

前端 未结 3 828
孤街浪徒
孤街浪徒 2021-01-03 06:10

I have a container div element, this should contain all child div elements. I saw this thread: Slide a div offscreen using jQuery and I was wondering how to implement it (wi

3条回答
  •  悲&欢浪女
    2021-01-03 07:07

    jQuery for the logic and CSS3 for transition and transform.
    Multiple galleries + Auto-slide + Pause on hover:

    $(function(){
    
      $('.gallery').each(function() {
    
        var $gal     = $(this),
            $movable = $(".movable", $gal), 
            $slides  = $(">*", $movable),
            N        = $slides.length,
            C        = 0,
            itv      = null;
        
        function play() { itv = setInterval(anim, 3000); }
        function stop() { clearInterval(itv); }
        function anim() {
          C = ($(this).is(".prev") ? --C : ++C) <0 ? N-1 : C%N;
          $movable.css({transform: "translateX(-"+ (C*100) +"%)"});
        }
        
        $(".prev, .next", this).on("click", anim);
        $gal.hover(stop, play);
        play();
    
      });
    
    });
    .gallery{
      position: relative;
      overflow: hidden;
    }
    .gallery .movable{
      display: flex;
      height: 70vh;
      transition: transform 0.4s;
    }
    .gallery .movable > div {
      flex:1;
      min-width:100%;
    }
    
    
    Pause on hover and autoslide
    
    
    
    As many galleries as you want

    Count the number of slides and put into a counter C.
    On prev/next click manipulate C
    On autoslide $(this).is(".prev") will also evaluate as false so ++C will be used, just like clicking the Next button.
    On mouseenter simply clearInterval the currently running itv and on mouseleave (the second .hover argument) reinitialize the itv

    The animation is achieved by multiplying C*100 and translateX by - C * 100 %

提交回复
热议问题