调整大小的动画侧边栏中断

时间:2015-07-21 02:43:09

标签: javascript jquery html css html5

我正在尝试构建一个动画侧边栏,当您单击按钮时可以滑入和滑出。这很容易实现,但是在制作侧边栏时我遇到了一个问题“更多'响应。基本上,我希望侧边宽度小于500时宽度为200px,否则宽度为300px。这是在媒体查询中完成的。我遇到的问题是,当您调整窗口大小时,如果您在调整大小之前已经运行了该功能,则侧边栏会偏离位置。

例如,如果用户在使用侧边栏时旋转其移动屏幕,则会出现此问题,因此我觉得最好尝试修复它。

这是jQuery:

function sidebar(){
    var menuWidth = $('#menu').width();
    if($('#menu-link').hasClass('hidden')){
            $('#menu-link').removeClass('hidden');
            $('.push').animate({right: "-=" + menuWidth});
        }else{
            $('#menu-link').addClass('hidden');
            $('.push').animate({right: "+=" + menuWidth});
        }

};

$('body').on('click', '#menu-link', sidebar);

侧边栏更改为200px <500,否则为300px。编写此代码的最佳方法是什么,或者最好通过始终使侧边栏200px保持简单,即使它在较大分辨率下不是美观的。

这是我的代码的JSFiddle的链接 https://jsfiddle.net/fqcydqu7/

编辑:抱歉,要清楚地解释实际问题 - 在调整大小之前,此代码运行正常并且非常完美。但是,如果您运行此代码(即打开并关闭侧边栏)然后调整窗口大小以使媒体查询处于活动状态,您将看到侧边栏位置偏离100px。如果您颠倒订单,则会发生相反的情况。

1 个答案:

答案 0 :(得分:0)

好的,我想出了解决问题的方法。

基本上,我从CSS中删除媒体查询并将div设置为始终为300px。 jquery使用一个变量,只要调整窗口大小就会更新该变量来判断滑动菜单的程度。 (200px或300px)。

这是代码:

// variable is set to 0 by default
var menuWidth = 0;
//call to function that will set this variable
setWidth();
function setWidth(){
    if(windowSize <= 800){ //if its less than 800px wide, set the variable to 200px (the menu is still 300px)
        menuWidth = "200px";
    }else{
        menuWidth = "300px"; //otherwise set the variable to 300px
    }
}
$(window).resize(function(){ //when a user resizes the window, run the setWidth function to readjust the variable
    setWidth(); //this re-runs setWidth

    //the following closes the menu if it's already open to avoid glitches
    if($('#menu-link').hasClass('hidden')){
    $('#menu-link').removeClass('hidden');
    $('.push').animate({right: "-=" + menuWidth});
}
});


 //nav slide
function sidebar(){
   if($('#menu-link').hasClass('showing')){ //checks to see if the nav is showing or not
            $('#menu-link').removeClass('showing'); //remove the showing tag
            $('.push').animate({right: "-=" + menuWidth}); //closes the nav
        }else{ //if the nav doesnt have showing tag it must be hidden
            $('#menu-link').addClass('showing'); //add the showing tag
            $('.push').animate({right: "+=" + menuWidth}); //open the nav
        }

};

使用此代码,当窗口宽度小于800px时,菜单将仅滑出200px,如果窗口宽度大于300px。即使用户旋转移动设备或更改窗口宽度,div也始终处于正确的位置。