您不能将
animate()方法与滚动功能一起使用,因为滚动值将始终更改并且jQuery无法无限重复相同的动画,因此会产生冲突。停止也无法挽救这个问题,或者我无法做到这一点。
$(window).scroll(function() { var scrollVal = $(this).scrollTop(); if ( scrollVal > offset.top) { $sidebar.css({'margin-top': (($window.scrollTop() - offset.top) + topPadding) + 'px' //added +'px' here to prevent old internet explorer bugs }); } else { $sidebar.css({'margin-top':'0px'}); }});注意:如果要使用扩展if语句
else if,请不要使用
else,这也会造成冲突。相信我,这个问题我真的很熟练。
更新:
您也可以将自己的appuouch更改为限额计算。我假设您要修复导航,并且您的html如下所示:
<div > <div >header</div> <span id="subnav">hold this</span></div>$(document).ready(function() { $(window).scroll(function() { var headerH = $('.header').outerHeight(true); //this will calculate header's full height, with borders, margins, paddings console.log(headerH); var scrollVal = $(this).scrollTop(); if ( scrollVal > headerH ) { //when scroll value reach to your selector $('#subnav').css({'position':'fixed','top' :'0px'}); } else { $('#subnav').css({'position':'static','top':'0px'}); } }); });


