在浏览器调整大小(视口宽度)上动态添加类

Edw*_*ard 5 javascript jquery

我有一个名为 jobfilter 的元素,我想根据视口宽度向其中添加一个类,即。当我将浏览器的大小调整为 <1000px 时,我想将类 .hidden 添加到 .jobfilter。

现在,我在此链接的帮助下设法让它半途而废:$(window).width() 与 media query 不同。使用这个:

  function checkPosition() {
    if (window.matchMedia('(max-width: 767px)').matches) {
        //...
    } else {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 JSFiddle:http : //jsfiddle.net/ck55Lf01/10/

如果您调整浏览器大小并刷新页面,jobfilter 会隐藏,但我希望动态发生,而不是在页面刷新时,谢谢您的帮助!

Lar*_*ane 4

这是我用来在调整大小时动态检查窗口宽度的函数,我将其包装在一个文档就绪函数中,该函数将 $ 作为参数传递,以防止与使用 $ 的其他 javascript 库可能发生的任何冲突。一个例子是,如果您要在 WordPress 主题或插件中使用您的函数。

Jsfiddle示例:http://jsfiddle.net/larryjoelane/ck55Lf01/24/

JavaScript:

/*
document ready function used to prevent conflict with other javascript libraries
that use the $ parameter
*/
jQuery(document).ready(function($){

     //get the window width
     var winWidth =  $(window).width();

      //set the maxWidth
     var maxWidth = 1000;

          //if the window width is less than the maxWidth pixels on document loading
          if(winWidth < maxWidth){//begin if then

            //add the class hidden to .jobFilter         
            $(".jobfilter").addClass("hidden");

         }//end if then



$(window).resize(function(){//begin resize event


    //get the window width
     var winWidth =  $(window).width();

      //set the maxWidth
     var maxWidth = 1000;    


         //if the window width is less than maxWidth pixels
         if(winWidth < maxWidth){//begin if then

            //add the class hidden to .jobFilter         
            $(".jobfilter").addClass("hidden");

         }
         else{

            //remove the class hidden                 
            $(".jobfilter").removeClass("hidden");


     }//end if then else


     });//end window resize event

});//end document ready function
Run Code Online (Sandbox Code Playgroud)