简体   繁体   English

jQuery-通过滚动位置进行动画处理以在窗口调整大小时保持相同

[英]Jquery - Animate by scroll positions to work the same on window resize

Hey I have this really annoying issue thats probably got a simple solution but for the life of me i cant find away to fix it. 嘿,我遇到了一个非常烦人的问题,这也许可以得到一个简单的解决方案,但是对于我的一生,我找不到解决的办法。

Basically i have two images both 50% with of it's container now the goal is the both images to slide in (left/right) on the basis of the scroll position and once it get to the top of the container both images will sit is place. 基本上,我有两个图像,两个图像都占其容器的50%,现在的目标是根据滚动位置将两个图像滑入(向左/向右),一旦到达容器顶部,两个图像将被放置。

Now i got that working to that point the only issue is when i resize the page the position of both images are wrong. 现在,我的工作到了这一点,唯一的问题是当我调整页面大小时,两个图像的位置都错误。 I obviously did a resize() function with the same logic as the scroll() function but still i got nowhere. 我显然做了一个resize()函数,它的逻辑与scroll()函数相同,但是我仍然一无所获。 Here's my code 这是我的代码

var page_width  =  $(document).outerWidth(),
            page_height =  $(document).outerHeight(),
            left_image  =  $('.split-screen.youth'),
            right_image =  $('.split-screen.elite'),
            offset      =  (page_width) / page_height;

        left_image.css({'left':'0px'});
        right_image.css({'right':'0px'});

        $(window).on('scroll', null, function(){
            var scrollTop =  $(window).scrollTop(),
                calc      =  -(scrollTop*offset); 

            left_image.css({
                'margin-left': 'calc(100% + '+calc+'px)'

            });

            right_image.css({
                'margin-right': 'calc(100% + '+calc+'px)'
            });
        });

        $(window).resize(function(){
            // something ???
        });

Here is a jsFiddle of the issue although it doesn't look entirely accurate but you get the picture. 这是问题的jsFiddle,尽管它看起来并不完全准确,但是您可以理解。 When you resize the scroll position changes and i need the margin-left/margin-right values to be correct. 当您调整滚动位置的大小时,我需要margin-left / margin-right值正确。

I think your problem is that you're still using the old offset value. 我认为您的问题是您仍在使用旧的偏移值。 Just update your global values first, than it works for me (see: https://jsfiddle.net/a7tfmp37/2/ ): 只需先更新您的全局值,即可使用对我有用的全局值(请参阅: https : //jsfiddle.net/a7tfmp37/2/ ):

 $(window).resize(function(){
    page_width  =  $(document).outerWidth(),
    page_height =  $(document).outerHeight(),
    offset      =  (page_width) / page_height;
    var scrollTop =  $(window).scrollTop(),
        calc      =  -(scrollTop*offset); 
    left_image.css({
        'margin-left': 'calc(100% + '+calc+'px)'

    });

    right_image.css({
        'margin-right': 'calc(100% + '+calc+'px)'
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM