我正在开发我的响应式菜单,该菜单将在桌面 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/