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

前端 未结 5 511
轻奢々
轻奢々 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:53

      [[ This example checks if ANY part of the element is inside the specified region ]]

      When you have the top and bottom coordinates of two boxes, you can check if the two boxes overlap by checking:

      box1.top < box2.bottom && box1.bottom > box2.top
      

      In the following example, box1 is the 30%-60% portion of window while box2 is each list item. Add debounce function and we have:

      var timeout;
      $(window).on("load scroll resize", function() {
        if (timeout) {
          clearTimeout(timeout);
        }
        timeout = setTimeout(function() {
          var $window = $(window),
            hitbox_top = $window.scrollTop() + $window.height() * .3,
            hitbox_bottom = $window.scrollTop() + $window.height() * .6;
          $("li").each(function() {
            var $element = $(this),
              element_top = $element.offset().top,
              element_bottom = $element.offset().top + $element.height();
            $element.toggleClass("middle-viewport", hitbox_top < element_bottom && hitbox_bottom > element_top);
          });
        }, 200);
      });
      #overlay {
        position: fixed;
        left: 0;
        top: 30%;
        width: 100%;
        height: 30%;
        background-color: rgba(0, 192, 255, .5);
      }
      ul {
        padding: 0;
        text-align: center;
      }
      li {
        display: inline-block;
        margin: 10px;
        width: 200px;
        height: 200px;
        background-color: #F5F5F5;
      }
      li.middle-viewport {
        background-color: #FF0000;
      }
      
      

    提交回复
    热议问题