我得到了我想要的行为:当用户向下滑动页面时,目标对象留在视口中(但始终保持在父容器内)。问题是用鼠标滚动时它会闪烁很多。看一看:
标记:
<div id='container'>
<div id='target'></div>
</div>
Javascript
(function($){
$(document).ready(function(){
// variables
var target = $('#target');
var targetRect = target[0].getBoundingClientRect();
var container = $('#container');
var contRect = container[0].getBoundingClientRect();
var viewportHeight = $(window).height();
// logic conditions
var topOffScreen = false;
var roomForTarget = false;
// scroll event
$(window).scroll(function(){
targetRect = target[0].getBoundingClientRect();
contRect = container[0].getBoundingClientRect();
winTop = $(window).scrollTop();
topOffScreen = (contRect.top < 0);
roomForTarget = (contRect.bottom > target.height());
// if container scrolls off top of viewport
if(topOffScreen && roomForTarget){
target.offset({top:winTop});
target.css('border', 'solid 3px green');
// if container fits in viewport entirely
} else if (roomForTarget) {
target.css('border', 'solid 3px green');
// more code here
// if container no longer fits in viewport
} else {
target.css('border', 'solid 3px red');
// more code here
}
});
});//end document.ready
})(jQuery);
我怎样才能让这不那么紧张?