Javascript 调整大小时不更新内部宽度

Javascript 调整大小时不更新内部宽度,javascript,html,responsive-design,innerhtml,Javascript,Html,Responsive Design,Innerhtml,我正在制作我的第一份响应菜单。我的一切都很好,但有一个问题我无法修复 我有菜单。当页面的宽度小于600像素时,它会变成一个下拉菜单。现在我有以下问题: 当我的菜单处于下拉模式(屏幕大小

我正在制作我的第一份响应菜单。我的一切都很好,但有一个问题我无法修复

我有菜单。当页面的宽度小于600像素时,它会变成一个下拉菜单。现在我有以下问题:

当我的菜单处于下拉模式(屏幕大小<600)时,它必须在您选择菜单项时立即折叠。我使用此代码来归档:

//check if the screen size < 600. if yes let menu hide on click.
if (window.innerWidth < 600) {// this is the code that gives me trouble
$( "#top-menu" ).click(function() {
       $( "#top-menu" ).hide();
      });
}

//toggle the menu when in small screen size. 

$( "#pull" ).click(function() {
$( "#top-menu" ).toggle();

});
//检查屏幕大小是否小于600。如果是,请让菜单在单击时隐藏。
如果(window.innerWidth<600){//这就是给我带来麻烦的代码
$(“#顶部菜单”)。单击(函数(){
$(“#顶部菜单”).hide();
});
}
//小屏幕时切换菜单。
$(“#拉动”)。单击(函数(){
$(“#顶部菜单”).toggle();
});
演示(不干净,但足以向您展示我的意思):


当我在屏幕中启动时,这可以正常工作您必须添加一个事件
onresize
进行检查,它不会在没有任何事件列表的情况下检查窗口的大小调整

 window.addEventListener('onresize',function(){  

      if (window.innerWidth < 600) {           
           $( "#top-menu" ).hide(); //i think you just need this only        
      } else {
           $( "#top-menu" ).show();
      }

  })
window.addEventListener('onresize',function(){
如果(window.innerWidth<600){
$(“#顶部菜单”).hide();//我想你只需要这个
}否则{
$(“#顶部菜单”).show();
}
})

将代码更改为:

//check if the screen size < 600. if yes let menu hide on click.
if (window.innerWidth < 600) {// this is the code that gives me trouble
$( "#top-menu" ).click(function() {
       $( "#top-menu" ).hide();
      });
}else if (window.innerWidth > 600){
    $( "#top-menu" ).click(function() {
     $( "#top-menu" ).show();
      });

}

//toggle the menu when in small screen size. 

$( "#pull" ).click(function() {
$( "#top-menu" ).toggle();

});
//检查屏幕大小是否小于600。如果是,请让菜单在单击时隐藏。
如果(window.innerWidth<600){//这就是给我带来麻烦的代码
$(“#顶部菜单”)。单击(函数(){
$(“#顶部菜单”).hide();
});
}否则如果(window.innerWidth>600){
$(“#顶部菜单”)。单击(函数(){
$(“#顶部菜单”).show();
});
}
//小屏幕时切换菜单。
$(“#拉动”)。单击(函数(){
$(“#顶部菜单”).toggle();
});

您必须将该代码包装在
onresize
窗口事件中,否则它不会在每次调整页面大小时执行,而是在运行时执行。