jQuery Behave like Media Queries when Resizing Browser?

 ̄綄美尐妖づ 提交于 2019-12-23 05:48:09

问题


I've been struggling with this for a while. Basically I have a div (#memberrevealwrapper) that is a specific height unless the viewport is less than 790px in width, then it is another height. (It's a responsive web design)

Now, #memberrevealwrapper is animated using jQuery to make it function like a pull tab that comes from the top of the browser upon click and then click again and it rolls back up.

Here is my jQuery:

<script>
    $(document).ready(function() {
        $('#memberloginrevealwrapper').animate({ marginTop: '-75px'}, 200);
        $('#memberloginlink a').toggle(
            function(){
                $('#memberloginrevealwrapper').animate({ marginTop: '0' }, 500);
            },
            function(){
                $('#memberloginrevealwrapper').animate({ marginTop: '-75px'}, 500);
            }
        );
    });

    $(document).ready(function(){
        var pageWidth = $(window).width();  

        if ( pageWidth <= 790 ) {

            $('#memberloginrevealwrapper').animate({ marginTop: '-147px' }, 200);
            $('#memberloginlink a').toggle(
                function(){
                    $('#memberloginrevealwrapper').animate({ marginTop: '0' }, 500);
                },
                function(){
                    $('#memberloginrevealwrapper').animate({ marginTop: '-147px'}, 500);
                }
            );

        }; 
    });

</script>

This works great until you resize the browser. When you resize the browser, it doesn't find the new height and to readjust the height.

Here is the site in action: clients.januarycreative.com/PES. I am referring to the "Member Login" tab at the top of the page.

Anyone know how I can get jQuery to refresh when the browser is resized? I've tried everything I know how, and have managed everything from cutting off the page to making the page bounce like a basketball many times in a row.

Thank you in advance!


回答1:


You need to re-run the code over again as the browser resizes. What you have up there just runs the code one on page load. You need a loop (technically an event that fires over and over again as the page resizes).

Here you go:

function updateSize() {
    var pageWidth = $(window).width();  

    if ( pageWidth <= 790 ) {
        $('#memberloginrevealwrapper').animate({ marginTop: '-147px' }, 200);
        $('#memberloginlink a').toggle(
            function(){
                $('#memberloginrevealwrapper').animate({ marginTop: '0' }, 500);
            },
            function(){
                $('#memberloginrevealwrapper').animate({ marginTop: '-147px'}, 500);
            }
        );
    }
}

$(window).resize(updateSize);


来源:https://stackoverflow.com/questions/14369944/jquery-behave-like-media-queries-when-resizing-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!