简体   繁体   English

如果屏幕宽度小于960像素,则将屏幕宽度添加到类中

[英]Add width of the screen to a class if screen width is less than 960 px

The code below adds width of screen to class .reverse 下面的代码将屏幕的宽度添加到类.reverse

var w = $(window).width();
 $('.reverse').css('width', w);

but I want it to do so only if the screen width is less than 960px: 但我希望只有在屏幕宽度小于960px时才这样做:

if ($(window).width() < 960) {
    $('.reverse').css('width', w);
}

The code above is not working, could you take a look? 上面的代码无法正常工作,您可以看看吗? Thx! 谢谢!

I think you are resizing window to check this effect so you need to add resize eventListener,to the DOM. 我认为您正在调整窗口大小以检查此效果,因此您需要向DOM添加调整大小的eventListener。

 $(window).on('resize',function(){
     var w=$(window).width();
    if (w< 960) {
        $('.reverse').css('width', w);
    }
    })

Try with jQuery 尝试使用jQuery

$(window).resize(function(){
  var width = $(window).width();
  console.log(width);
  if (width < 960){
    $('.reverse').css('width', width);
  };
});

This way you're constantly checking the window's width while resizing as well. 这样,您就可以在调整大小的同时不断检查窗口的宽度。

You can also do this with CSS and a media query if you don't have to use javascript 如果不必使用javascript,也可以使用CSS和媒体查询来执行此操作

@media (max-width: 960px) {
  .reverse {
    width: 100vw;
  }
}
var w = $(window).width();
if (w < 960) {
    $('.reverse').css('width', w);
}

Note, add the event management if needed but no w was defined. 注意,如果需要,请添加事件管理,但未定义w

IF you add the event management in, be careful as it will fire a lot and it would be best to NOT force a re-flow every time - look into that separate issue. 如果您添加了事件管理,请小心,因为它将触发很多事件,并且最好不要每次都强制重排-查看该单独的问题。

A link to a possible debounce for the resize https://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/ 可能调整大小的防反跳的链接https://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/

  if ($(window).width() < 960) { $('.reverse').css('width', w); } 

You didn't initialize w 您没有初始化w

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

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