ウィンドウとコンテンツの各スクロール位置を取得する

by iwbjp

HTML

<div id="result"></div>
<div id="result2"></div>

<div class="content c1">コンテンツ 1</div>
<div class="content c2">コンテンツ 2</div>
<div class="content c3">コンテンツ 3<span id="end">終わり</span></div>

CSS

* {
  margin: 0;
  padding: 0;
}

h1 {
  margin-bottom: 1000px;
}

.content {
  height: 1000px;
  font-size: 50px;
}

.c1 {
  background: #FCF;
}

.c2 {
  background: #D5FFB9;
}

.c3 {
  position: relative;
  background: #DFF;
}

#result {
  position: fixed;
  top: 0;
  right: 0;
  width: 200px;
  padding: 50px 0;
  font-size: 30px;
}

#result2 {
  position: fixed;
  top: 100px;
  right: 0;
  width: 200px;
  font-size: 12px;
  line-height: 1.5;
}

#end {
  display: none;
  position: absolute;
  bottom: 0;
  left: 0;
  font-size: 100px;
}

JavaScript

$(function(){
  var contentTop = [];
  var contentHeight = [];
  var current = -1;
  var scrollBottom;
  
  $(".content").each(function(i){
    contentTop[i] = $(this).offset().top;
    contentHeight[i] = $(this).height();
  });
  
  function getScrollTop(){
    scrollBottom = $(window).scrollTop() + $(window).height();
    
    for(var i=contentTop.length-1; i>=0; i--){
      
      $("#result2").html(
        'スクロール上の上位置:' + 
        ($(window).scrollTop()+$(window).height()) + 
        '<br>各コンテンツの上位置:' + 
        contentTop[i]
      );
      
      if(scrollBottom > contentTop[i]){
        changeBox(i);
        break;
      }
    }
  }
  
  function changeBox(num){
      
    if(num != current){
      current = num;
    }
    
    if(current == 0){
      $("#result").text("コンテンツ 1");
    }
    else if(current == 1){
      $("#result").text("コンテンツ 2");
    }
    else if(current == 2){
      $("#result").text("コンテンツ 3");
      
      var contentBottom = contentTop[current] + contentHeight[current];
      
      if(scrollBottom == contentBottom){
        $("#end").fadeIn();
      }
    }
  }
  
  $(window).on('load scroll resize', getScrollTop);
});