栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

当div#滚动到视图中时,jQuery在导航上更改CSS

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

当div#滚动到视图中时,jQuery在导航上更改CSS

我没有看过代码示例(挑战自己: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

脚本:

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');   }  }); });});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/575789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号