Jquery根据浏览器宽度进行更改

时间:2013-12-06 05:44:06

标签: javascript jquery css width browser-width

如果浏览器宽度>我希望Div标记为空760像素和不到980像素,但看起来我做错了

    (function($){

  //detect the width on page load
  $(document).ready(function(){

    var current_width = $(window).width();
     //do something with the width value here!
    if(current_width < 980 && current_width > 760){
       $('#chwd').empty();
    }
  });

  //update the width value when the browser is resized (useful for devices which switch from portrait to landscape)
  $(window).resize(function(){
    var current_width = $(window).width();
   //do something with the width value here!

    if(current_width < 980 && current_width > 760  ){
         $('#chwd').empty();
    }
    else{
        $('#chwd').html(

<div id="ahead">
<div class="column">
Cash On Delivery
</div>
</div>

        );}
  });

})(jQuery);

任何帮助都会得到赞赏

Thanx

4 个答案:

答案 0 :(得分:0)

使用outerWidth代替width,它包括填充和边框。您还需要将div包装在“”中,否则html()会认为它是变量。

答案 1 :(得分:0)

您的脚本没问题,问题在于如何构建$('#chwd').html()

Javascript以不同方式处理新行。与PHP或其他语言不同,它允许您继续使用新行,只要它包含引号/单引号。在Javascript每次你做一个新行时,你必须用''和+包装它(见我的代码)

这是可以接受的

'Lorem' +
'Ipsum'

这是不可接受的

'Lorem
 Ipsum'

试试这个:

 (function($){

  //detect the width on page load
  $(document).ready(function(){

    var current_width = $(window).width();
     //do something with the width value here!
    if(current_width < 980 && current_width > 760){
       $('#chwd').empty();
    }
  });

  //update the width value when the browser is resized (useful for devices which switch from portrait to landscape)
  $(window).resize(function(){
    var current_width = $(window).width();
   //do something with the width value here!

    if(current_width < 980 && current_width > 760  ){
         $('#chwd').empty();
    }
    else{
        $('#chwd').html('<div id="ahead">'+
'<div class="column">'+
'Cash On Delivery'+
'</div>'+
'</div>');
    }
  });

})(jQuery);

答案 2 :(得分:0)

将你改为:

else{
   $('#chwd').html('<div id="ahead"><div class="column">Cash On Delivery</div></div>');
}

答案 3 :(得分:0)

在else语句中尝试:

else
{
    var divString = '<div id="ahead"><div class="column">'+
                    'Cash On Delivery'+
                    '</div></div>';
    $('#chwd').html(divString);
}

希望这有帮助。