【JavaScript】シングルページで現在地を示すドットのナビゲーションを実装する方法のデモページ

※デベロッパーツール等でソースコードをご確認ください(Please check using Developer tools)

このページの内容が難しいと感じた方はこちら

スポンサーリンク

Web制作会社LIGが運営するWebデザインスクール

CSS

.wrap {
  width: 100%;
}

.nav-dot {
  position: fixed;
  top: 50%;
  right: 3%;
  z-index: 1;
}

.nav-dot li {
  width: 6px;
  height: 6px;
  margin: 0 0 14px;
  background: rgba(58, 58, 58, 0.2);
  border-radius: 50%;
  cursor: pointer;
  transition: background 0.7s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;
}

.nav-dot li.current {
  background: rgba(58, 58, 58, 0.5);
  transition: background 0.7s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;
}

.nav-dot li:last-child {
  margin: 0;
}

.block {
  height: 800px;
}
  

JavaScript

$(window).on("load",function(pager){
  var eventElemArray = [];
  var _count = 0;
  var _countFix = 0;
  $(window).on('load scroll resize',function(){
    eventElemArray = [];
    _count = 0;
    $('[data-nav]').each(function(i,pager){
      eventElemArray.push( $(pager).offset().top );
    });
    for(var _i = 0;_i < eventElemArray.length; _i++){
      if( $(window).scrollTop() + ($(window).height() * 0.5) > eventElemArray[_i] ){
        _count++;
      }
    }
    if(_count !== _countFix){
      _countFix = _count;
      $('.nav-dot li').removeClass('current');
      $('.nav-dot li').eq(_count-1).addClass('current');
    }
  });

  $('.nav-dot li').on('click', function() {
    var speed = 700;
    var href = $(this).attr('data-nav-href');
    var offset = $(this).attr('data-nav-offset')|0;
    var target = $(href == '' ? 'html' : href);
    var position = target.offset().top + offset
    $('body,html').animate({scrollTop:position}, speed);
    return false;
  });
});