Prevent page from jumping while changing position

2019-08-10 17:00发布

I have a video on my site and a window scroll function. When somebody scrolls under the video and is at level of a fake div element, the video is changing position from relative to fixed and then comes back on scrolling to the top. The problem is that the page jumps whenever I do it (because the element is removed and placed somewhere else). I tried to use animate and fadeOut functions but these didn't seem to help.

Check out this fiddle for what I mean:

https://jsfiddle.net/xwgza7qf/2/

var h = $('#fake-element').position().top;
console.log(h);
            $(window).scroll(function(){
                var y = $(window).scrollTop();
                if( y > h){
                    $('#video').css({
                        'position' : 'fixed',
                        'display' : 'block',
                        'left' : '50px',
                        'width' : '50px',
                        'top' : '45px'
                    });
                } else {
                    $('#video').css({
                        'position' : 'relative',
                        'display' : 'block',
                        'left' : '0px',
                        'width' : 'auto',
                        'top' : '0px'
                    });
                }
            });

When you scroll to the moment (fake div) where #video goes to fix position, the page jumps, the scrolling is not smooth. How can I achieve the effect of smooth scrolling in this case. I want to do something like on this site:

http://www.cnn.com/2016/02/01/politics/iowa-caucuses-2016-highlights/index.html

but have no idea how they achieved this (video goes to fixed to the right sidebar on scrolling and scrolling is still smooth, works perfect on Firefox).

0条回答
登录 后发表回答