当div#滚动到视图中时,jQuery在导航时改变css

Mr *_*ood 7 css jquery height

我想重新创建在这个网站上使用的效果:http://www.brizk.com/

该网站使用一个向下滚动的大页面.当您向下滚动并传递不同的部分时,左侧的菜单导航将css类更改为"当前",因为相应的div进入视图.

我认为这可以通过jQuery使用$(window).height();

我是jQuery的新手,我想写的是这样的(用非专业术语来说):

  • 获取浏览器窗口的高度 - 如果div#content1从顶部100px和/或​​从底部更改菜单200px a#link1到'.current' - 否则从所有菜单中删除.current链接

...并重复4个不同的内容div.

任何人都可以指出我正确的方向..?谢谢.

Mot*_*tie 24

我没有看代码示例(挑战自己更有趣:P)但这就是我要做的 - 演示在这里.

我保存了每个元素块的位置以最小化DOM调用的数量,然后只搜索数组.帮助您了解一些变量.

$(window).height() // returns the viewport height
$(document).height() // returns the height of the entire document
$(window).scrollTop() // returns the Y position of the document that is at the top of the viewport
Run Code Online (Sandbox Code Playgroud)

脚本:

var topRange      = 200,  // measure from the top of the viewport to X pixels down
    edgeMargin    = 20,   // margin above the top or margin from the end of the page
    animationTime = 1200, // time in milliseconds
    contentTop = [];

$(document).ready(function(){

 // Stop animated scroll if the user does something
 $('html,body').bind('scroll mousedown DOMMouseScroll mousewheel keyup', function(e){
  if ( e.which > 0 || e.type == 'mousedown' || e.type == 'mousewheel' ){
   $('html,body').stop();
  }
 });

 // Set up content an array of locations
 $('#sidemenu').find('a').each(function(){
  contentTop.push( $( $(this).attr('href') ).offset().top );
 });

 // Animate menu scroll to content
  $('#sidemenu').find('a').click(function(){
   var sel = this,
       newTop = Math.min( contentTop[ $('#sidemenu a').index( $(this) ) ], $(document).height() - $(window).height() ); // get content top or top position if at the document bottom
   $('html,body').stop().animate({ 'scrollTop' : newTop }, animationTime, function(){
    window.location.hash = $(sel).attr('href');
   });
   return false;
 });

 // adjust side menu
 $(window).scroll(function(){
  var winTop = $(window).scrollTop(),
      bodyHt = $(document).height(),
      vpHt = $(window).height() + edgeMargin;  // viewport height + margin
  $.each( contentTop, function(i,loc){
   if ( ( loc > winTop - edgeMargin && ( loc < winTop + topRange || ( winTop + vpHt ) >= bodyHt ) ) ){
    $('#sidemenu li')
     .removeClass('selected')
     .eq(i).addClass('selected');
   }
  });
 });

});
Run Code Online (Sandbox Code Playgroud)

  • 只是为了让你知道,我已经改进了代码并将其变成了一个插件:https://github.com/Mottie/visualNav - 演示链接在底部,嗯,我会把它移动到make它更容易找到. (2认同)