Why doesn't my jQuery respond to window resize?

£可爱£侵袭症+ 提交于 2019-12-08 04:16:13

问题


I'm using jQuery to add some make some elements on a page transition (via the jQuery Transit plugin) when hovered upon. Since I'm trying to design responsively, I want these transitions to only happen when the browser is a certain size or larger.

I've written the following code as an attempt to do this:

$(document).ready(function(){
    var $window = $(window);
    var $logo = $('.logo');

    function checkWidth() {
        windowsize = $window.width();
    }

    checkWidth();

    $(window).resize(checkWidth);

    if (windowsize >= 768) {
        $logo.hoverIntent(
            function(){
                $logo.transition({
                    perspective: '600px',
                    rotateY: '-10deg'
                });
            },
            function(){
                $logo.transition({
                    perspective: '600px',
                    rotateY: '0deg'
                });
            }
        );
    }

});

If I load the page in a large browser, it works as expected--the hover effect is active. If I resize the browser, making it smaller (past the breakpoint) and refresh, then it works--the hover effect is disabled. But if I resize the window without refreshing in between, then the effect doesn't respond--it either remains disabled (if resizing from a small to a large screen) or active (if resizing from large to small).

It's a minor quirk, to be sure, but I can't exactly figure out why it's happening. As far as I can tell, when the window resizes, it should be updating the windowsize variable, which should be checked in the if statement. What am I overlooking that makes this not the case?

Thanks a bunch.


回答1:


All checkWidth currently does is assign a value to windowsize. You need to move the code that actually reads windowsize into checkWidth.

$(document).ready(function(){
    var $window = $(window);
    var $logo = $('.logo');

    function checkWidth() {
        windowsize = $window.width();

        if (windowsize >= 768) {
            $logo.hoverIntent(
                function(){
                    $logo.transition({
                        perspective: '600px',
                        rotateY: '-10deg'
                    });
                },
                function(){
                    $logo.transition({
                        perspective: '600px',
                        rotateY: '0deg'
                    });
                }
            );
        }
    }

    // can trigger the resize handler instead of
    // explicitly calling checkWidth()
    $(window).resize(checkWidth).resize();
});


来源:https://stackoverflow.com/questions/17537714/why-doesnt-my-jquery-respond-to-window-resize

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