Fade in each li one by one

后端 未结 3 1942
春和景丽
春和景丽 2020-12-24 07:14

I want to fade each nav li one by one. Here\'s my current code. It shows the whole div, now I want to fade in each li one by one with a slight dela

相关标签:
3条回答
  • 2020-12-24 07:52

    You can use an each() call to loop through the li elements and delay() the fadeIn() animation by an incremental amount. Try this:

    $("#dropDownMenu li").each(function(i) {
        $(this).delay(100 * i).fadeIn(500);
    });
    .sub-menu {
        position: absolute;
        z-index: 1000;
        /* color: #fff;
        right: 5px; */
    }
    
    .sub-menu li {
        display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="sub-menu" id="dropDownMenu">
        <ul id="navbar">
            <li> First</li>
            <li>Second</li>
            <li>Third</li>
            <li>Fourth</li>
            <li>Fifth</li>
        </ul>
    </div>

    If you want to increase/decrease the interval between items fading, change the value provided to the delay() method. In this example I used 100ms.

    0 讨论(0)
  • 2020-12-24 07:53

    If you have a limited number of elements you could also consider using css-animations instead of a javascript solution. You can address each element using the nth-child selector and delay its animation according to its position. To make the animation stop at the end use the animation-fill-mode property.

    li {
      opacity: 0;
      animation: fadeIn 0.9s 1;
      animation-fill-mode: forwards;
    }
    
    li:nth-child(5n+1) {
      animation-delay: 0.5s;
    }
    
    /*...*/
    
    @keyframes fadeIn {
      0% {
        opacity: 0.0;
      }
      100% {
        opacity: 1.0;
      }
    }
    

    See this example and mind the prefixes https://jsfiddle.net/97bknLdu/

    0 讨论(0)
  • 2020-12-24 08:01

    Do something like this with animation success callback

    $(document).ready(function() {
      function fade(ele) {
        ele.fadeIn(500, function() { // set fade animation fothe emlement
          var nxt = ele.next(); // get sibling next to current eleemnt
          if (nxt.length) // if element exist
            fade(nxt); // call the function for the next element
        });
      }
      $("#circleMenuBtn").click(function() {
        fade($('#navbar li').eq(0)); // call the function with first element
      });
    });
    .sub-menu {
      left: 0;
      top: 0;
      position: relative;
      z-index: 1000;
      color: #000;
      right: 5px;
    }
    ul li {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="sub-menu" id="dropDownMenu">
      <ul id="navbar">
        <li>First</li>
        <li>Second</li>
        <li>Third</li>
        <li>Fourth</li>
        <li>Fifth</li>
      </ul>
    </div>
    <button id="circleMenuBtn">click</button>

    0 讨论(0)
提交回复
热议问题