0

我得到了我想要的行为:当用户向下滑动页面时,目标对象留在视口中(但始终保持在父容器内)。问题是用鼠标滚动时它会闪烁很多。看一看:

http://jsfiddle.net/3ZQat/5/

标记:

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

我怎样才能让这不那么紧张?

4

1 回答 1

0

“你可以在这里查看.. jsfiddle.net/nqZu2/2 可能不是你想要的一切.. 但应该给你一些想法。”

从评论。谢谢

于 2013-09-18T21:11:27.857 回答