Before after resize event

前端 未结 3 2078
悲&欢浪女
悲&欢浪女 2020-12-19 20:27

I would like to do something before and after resizing element, i have tried to bind resize event and it work:

$(\'#test_div\').bind(\'resize\', function(){
         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 20:50

    You could also try another method.

    First create a method to get the active breakpoint (mobile, tablet, desktop, desktop-large) ie Breakpoint.getActive()

    Then use an array to save the last two states recorded while resizing.

    Example code:

    var beforeAfterResize = [];
    $(window).resize(function() {
    
    var resizeInfo = Breakpoint.getActive();
    if (beforeAfterResize.length > 1) {
        beforeAfterResize[0] = beforeAfterResize[1];
        beforeAfterResize[1] = resizeInfo;
    } else {
        beforeAfterResize.push(resizeInfo);
    }
    console.log(beforeAfterResize);
    
    });
    

    The array called beforeAfterResize will only store two values in positions 0 and 1. If you have more than 2 values, then position 0 takes in the value of position 1 and position 1, the latest value, will retain the current breakpoint info.

    This way you will be able to have a before/after comparison without the timeout thingy.

    After the resize you will be able to compare values between beforeAfterResize[0] and beforeAfterResize[1] and, if they are different, you can do some actions.

    Example: let's say I want to know if after resize i moved from mobile to desktop or large desktop. Then I will use something like this:

        var fromMobile = false;
    if ( (( beforeAfterResize[0] === "mobile" ) || ( beforeAfterResize[0] === "tablet" ))  
        && (( beforeAfterResize[1] === "desktop" ) || ( beforeAfterResize[1] === "desktop-large" )) ) {
        fromMobile = true;
    }
    

    Let me know if this worked for you.

提交回复
热议问题