List rotation with limited elements

前端 未结 6 878
一向
一向 2021-02-04 04:18

I have div container with list (cards) inside. When I hover it, cards start to moving (translateX animation). container\'s width

6条回答
  •  执笔经年
    2021-02-04 04:20

    If you don't want to modify the dom elements you could take advantage of flex-item's order property;

    to do this you'd still need a little JS to add this property after animation has ended;

    I also changed to animation instead of transition so it automatically resets the transform property at the end of animation.

    $('.cards').mouseenter(function() {
      setTimeout(function() {
        $('.card').first().css("order", "2");
      }, 3000);
    });
    
    $('.cards').mouseleave(function() {
      $('.card').first().css("order", "-1");
    });
    .container {
      width: 300px;
      height: 100px;
      border: 2px solid black;
      overflow: hidden;
    }
    .card {
      float: left;
      /* height: 100px;
        width: 100px;*/
      background-color: blue;
      box-sizing: border-box;
      border: 2px solid red;
      color: white;
      font-size: 23px;
      flex: 0 0 25%;
    }
    .cards:hover {
      animation: trans 3s;
    }
    /**/
    
    .cards {
      width: 400px;
      height: 100%;
      display: flex;
      transition: transform 3s;
    }
    @keyframes trans {
      0% {
        transform: translateX(0)
      }
    
      100% {
        transform: translateX(-100px)
      }
    }
    
    
    
    1
    2
    3

    fiddle


    But if you're OK to use JS I suggest you manipulate the order of DOM elements directly,taking the first child element of .cards and appending it to the end of list at the end of each animation;

    try this:

    var anim;
    
    $('.cards').mouseenter(function(){
            
        anim = setInterval(function(){
            $('.cards').append($('.card').first())
        },3000)
        	
    });
    
    $('.cards').mouseleave(function(){
        clearInterval(anim)                   
    });
    .container{
        width:300px;
        height: 100px;
        border: 2px solid black;
        overflow: hidden;
    }
    .card{
        float:left;
       /* height: 100px;
        width: 100px;*/
        background-color:blue;
        box-sizing: border-box;
        border: 2px solid red;
        color: white;
        font-size: 23px;
        /**/
        flex:0 0 25%;
    }
    .cards:hover{
        animation: trans 3s infinite;
    }
    
    /**/
    .cards{
        width:400px;
        height:100%;
        display:flex;
    }
    
    
    @keyframes trans {
      0% {
        transform: translateX(0)
      }
      100% {
        transform: translateX(-100px)
      }
    
    }
    
    
    1
    2
    3


    in case you want one card to be present at same time both at the beginning and at the end of card-list you'll need to make a deep-copy / clone of the element;

    here's an example;

提交回复
热议问题