javascript - 我的响应式菜单出现故障

标签 javascript jquery html css

我正在开发我的响应式菜单,该菜单将在桌面 View 中显示为普通的水平菜单,但当屏幕小于 992 像素时,将出现一个汉堡包样式的按钮,该按钮将切换一个插入式侧边菜单。

我面临的问题是,在调整窗口大小时,也就是在桌面和移动 View 之间切换时,菜单出现故障。

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Menu</title>
<meta charset="utf-8"> 
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>

<div class="container">

我的CSS:

@media screen and (min-width: 992px) {

}

和我的js:

$(document).ready(function(){
    $('#mobile-icon').click(function(){
        $(this).toggleClass('closed');
    });

    $('.expander-icon').click(function(){
        $(this).parent().toggleClass('active-menu');

    });

});

$(window).on('load resize', function () {
    var screenWidth = $( window ).width();
    if(screenWidth < 992){
        $('.u').addClass('isMobile');

        $('#icon').click(function(){
            $(this).toggleClass("open closed");
            if($( "#con" ).hasClass( "open" )){
                $('.gation').css('margin-left',"0");

            }
            else{
                $('.asdn').css('margin-left',"-70%");
            }
        });


    }
});

最佳答案

简化您的 JS,将所有可以移动到 CSS 的东西。不要在 JS 中修改 margin,而是在 CSS 中修改,每当你在 mr-mobile-icon 上切换类 open 时,也在 mr-navigation< 上切换它。您的 $(window).on('load resize', ... ); 是不必要的。只需删除它,让 CSS 为您完成一切。

CSS:

@media screen and (max-width: 991px) {
    .mr-navigation {
        // style
        margin-left: -70%;
    }
    .mr-navigation.opened {
        margin-left: 0;
    }
}

JS:

$('#mr-mobile-icon').click(function(){
    $(this).toggleClass('open');
    $('.mr-navigation').toggleClass('open');
});

关于javascript - 我的响应式菜单出现故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44955029/

相关文章:

javascript - 使用 Jquery 动态添加一个元素到我的表单

html - 如何将调整窗口大小的表行堆叠到一列中?

javascript - 对象的对象作为函数参数

javascript - 带缩略图和灯箱的 jQuery 图片库

javascript - 将控制台日志写入文件直至达到一定大小

javascript - 使用jquery更改另一个元素下的html元素类

javascript - XSS:这如何安全?

html - 不能在 svg 的中心制作 g

javascript - jQuery $.get 返回完整的对象与我需要的

javascript - 如何在 sencha touch 中使用 Ext.ux.touchcalendar 中的 css 更改特定单元格颜色