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

时间:2014-01-28 08:56:48

标签: javascript html responsive-design innerhtml

我正在构建我的第一个响应式菜单。我把一切都运行得很好,但有一点我不能修复。

我有一个菜单。当页面宽度小于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();

});

演示(不干净,但足以告诉你我的意思):http://jsfiddle.net/skunheal/r4tdm/

当我在屏幕上显示&lt; 600 px时,此功能正常。但是,只要我将浏览器扩展为800像素,它仍然会在点击时隐藏菜单。我的代码说if (window.innerWidth < 600) {

如果我以800px刷新页面,如果我将其缩小到<600像素,它将不会隐藏我的菜单。

我的结论是window.innerWidth在调整浏览器窗口大小时不会自行更新。有人有建议吗?

2 个答案:

答案 0 :(得分:2)

您必须添加一个事件onresize进行检查,它不会检查窗口大小调整而没有任何事件列表器

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

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

  })

答案 1 :(得分:0)

将您的代码更改为:

//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();

});