ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-05-28 15:22:05  阅读:145  来源: 互联网

标签:jquery javascript


我有一个名为jobfilter的元素,我想根据视口宽度添加一个类,即.当我将浏览器的大小调整为< 1000px时,我想将类.hidden添加到.jobfilter. 现在,我设法在这个链接的帮助下完成了半工作:$(window).width() not the same as media query.
使用这个:

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

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

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

解决方法:

这是我用来动态检查resize上的窗口宽度的一个功能,我将它包装在一个文件就绪函数中,该函数将$作为参数传递,以防止与使用$的其他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

标签:jquery,javascript
来源: https://codeday.me/bug/20190528/1171859.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有