简体   繁体   English

为什么jQuery调整大小不起作用?

[英]why is jquery resize not working?

I am making a responsive menu. 我正在制作一个响应式菜单。 I put the code to change the menu in a function called file. 我将代码更改为一个名为file的函数来更改菜单。 when the document or the window are resized Jquery call the function file again to change the menu. 当调整文档或窗口的大小时,jQuery再次调用函数文件以更改菜单。 but that does not work. 但这不起作用。 when I load the page it works but on resize it don't. 当我加载页面时,它可以工作,但在调整大小时却不能。

Jquery: jQuery:

var width = $(window).width();

file();
function file(){
  if(width <= 400){
      $('.link').remove();
      $('head').append('<link class="link" rel="stylesheet" href="nav2.css">');
  }else if(width >400){
      $('.link').remove();
      $('head').append('<link class="link" rel="stylesheet" href="nav.css">');

  }else{
      alert('error');
  }
}
$(window).resize(function(){
  file();
});

$(document).resize(function(){
  file();
});

can somebody help me with fixing this problem 有人可以帮我解决这个问题吗

Your width variable isn't going to change once it's set. width变量一旦设置就不会更改。 You should move that inside the function declaration. 您应该将其移入函数声明中。

function file(){
  var width = $(window).width();
  if(width <= 400){
    $('.link').remove();
    $('head').append('<link class="link" rel="stylesheet" href="nav2.css">');
  }else if(width >400){
    $('.link').remove();
    $('head').append('<link class="link" rel="stylesheet" href="nav.css">');
 }else{
  alert('error');
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM