简体   繁体   中英

Check when an ENTIRE element is in view

How can I check when an entire element is in view?

In the example below, if a box comes into view, I want to change the background color of the box to red. Also, the top box (which should already be fully displayed on your screen) should automatically be red (since it's already fully in the view).

How can I do this?

https://jsfiddle.net/7gr1qkeq/

HTML:

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

CSS:

body {
  margin: 50px;
}

.container {
  width: 300px;
  background: lightgrey;
  padding: 50px;
}

.box {
  display: block;
  width: 100%;
  height: 300px;
  background: grey;
}

.box:not(:last-of-type) {
  margin-bottom: 50px;
}

Quick example. Not perfect code by any means. Should give you an idea.

checkBoxes();

$(window).on('scroll', function() {
    checkBoxes();
});

function checkBoxes() {
    $('.box').each(function(i, v) {
      if (_isInTheScreen($(window), $(v), -$(v).height() )) {
        $(v).css('background', 'red');
      }
    });
}

/*
 * @param $ct : container - jQuery obj
 * @param $el : element selected - jQuery obj
 * @param optionOffset : offset
 */
function _isInTheScreen($ct,$el,optionOffset) {
  var i = $ct,
      g = $el,
      e = i.scrollTop(),
      d = i.scrollLeft(),
      f = g.offset(),
      l = f.top,
      c = f.left,
      j = true;

  j = (e-100<=(l))&&((e+i.height()+optionOffset)>=((l))&&(d<=c)&&((d+i.width())>=c));
  return j;
}

NOTE: you should always throttle when binding on scroll

fiddle here: https://jsfiddle.net/cd2733mv/2/

If you just want to check if the elements are within window height, not necessarily window width:

function highlightBoxes() {
  var windowStart = $(window).scrollTop();
  var windowEnd = windowStart + $(window).height();

  $('.box').each(function() {
    var box = $(this);
    var start = box.offset().top;
    var end = start + box.height();

    if (windowStart <= start && windowEnd >= end) {
      box.addClass('active');
    } else {
      box.removeClass('active');
    }
  });
}

highlightBoxes();
$(document).scroll(highlightBoxes);
$(window).resize(highlightBoxes);

Fiddle: https://jsfiddle.net/7gr1qkeq/4/

Edit:

If you want to check complete visibility , ie width + height: https://jsfiddle.net/7gr1qkeq/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM