Check if element is between 30% and 60% of the viewport

前端 未结 5 513
轻奢々
轻奢々 2020-11-30 03:28

I am trying to change the color of

  • elements when they are between 30% and 60% of the viewport.

    So I have this grid of elements stacking side

  • 5条回答
    •  攒了一身酷
      2020-11-30 03:51

      1. Use scroll event handler on window
      2. Loop over all the li elements to check if the element is in the interested viewport
      3. Get the li position from top and check if it is in the interested viewport section.

      Demo:

      Changed the height of li for demo purpose.

      See the comments inline in the code.

      $(document).ready(function() {
        // Get viewport height, gridTop and gridBottom
        var windowHeight = $(window).height(),
          gridTop = windowHeight * .3,
          gridBottom = windowHeight * .6;
      
        $(window).on('scroll', function() {
          // On each scroll check if `li` is in interested viewport
          $('ul li').each(function() {
            var thisTop = $(this).offset().top - $(window).scrollTop(); // Get the `top` of this `li`
      
            // Check if this element is in the interested viewport
            if (thisTop >= gridTop && (thisTop + $(this).height()) <= gridBottom) {
              $(this).css('background', 'red');
            } else {
              $(this).css('background', 'gray');
            }
          });
        });
      });
      ul {
        margin: 0;
        list-style-type: none;
        padding: 0;
      }
      ul li {
        width: 50px;
        height: 30px;
        background: #f5f5f5;
        float: left;
        margin: 10px;
        text-align: center;
        padding-top: 10px
      }
      ul li.middleviewport {
        background: red;
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20

    提交回复
    热议问题