javascript - jquery 根据浏览器宽度改变

标签 javascript jquery css width browser-width

如果浏览器宽度 > 760 像素且小于 980 像素,我希望 Div 标签为空,但看起来我做错了什么

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

任何帮助将不胜感激

谢谢

最佳答案

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

Javascript 以不同方式处理新行。与 PHP 或其他语言不同,只要它用引号/单引号引起来,您就可以继续放置新行。在 Javascript 中,每次换行时,都必须用 '' 和 + 将其包裹起来(参见我的代码)

这是可以接受的

'Lorem' +
'Ipsum'

这是 Not Acceptable

'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);

关于javascript - jquery 根据浏览器宽度改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20416871/

相关文章:

php - 基于服务器端逻辑有条件地回显 Javascript 代码是否被认为是有害的?

javascript - Bootstrap 导航,长链接在 IE 中分两行,在其他情况下很好。怎么修?

css - 需要解决响应式布局的 em 和 rem 单元问题

html - 如何使所有跨浏览器兼容倾斜的 div 边缘?

php 中的 javascript - 失败

javascript - JavaScript 对象可以返回值和控制台日志吗?

javascript - 我可以用 Bootstrap 做一个部分吗?

jquery - 带有 CSS 或 jQuery 的非常宽的薄花括号

javascript - 使用 jQuery 通过 id 列表获取多个元素

css - 跨度左对齐文本 "around"其他跨度文本