Hide or remove a div class at mobile viewport?

ε祈祈猫儿з 提交于 2020-01-01 06:54:06

问题


First and foremost, I am very aware of CSS media queries. My problem is this: When you have div classes stacked in one div; Example:

<div class="class1 class2"></div>

And you want to remove "class2" @media (max-width: 768px) Creating an output of:

<div class="class1"></div>

...once the 768px threshold has been reached.

So far I have come up with nothing other than this non-functional code:

<script>
 jQuery(document).resize(function () {
  var screen = $(window)    
   if (screen.width < 768) {
    $(".class2").hide();
  }
     else {
       $(".class2").show();
      }
  });
</script>

I am really having a hard time finding an answer that works for this. I do not want to block the entire div's contents! Just remove one of two classes.


回答1:


I'm not sure I get this, but are you just trying to toggle a class?

$(window).on('resize', function () {
    $('.class1').toggleClass('class2', $(window).width() < 768);
});

FIDDLE

jQuery has addClass(), removeClass() and toggleClass() methods readily available.

Note that screen is already defined in javascript.




回答2:


Use the jQuery .removeClass() method:

 $(document).resize(function () {
     var screen = $(window);  

     if (screen.width < 768) {
         $('div').removeClass('class2');
     } else {
         $('div').addClass('class2');
     }

OR:

     screen.width < 768 ? $('div').removeClass('class2') : $('div').addClass('class2');
  });



回答3:


$(".class2").removeClass("class2")

And you should listen to the window not the document, so you can modify your code to the following:

<script>
 jQuery(window).resize(function () {
  var screen = $(window)    
   if (screen.width < 768) {
    $(".class2").removeClass("class2");
  }
     else {
       $(".class1").addClass("class2");
      }
  });
</script>

Of course, this will only toggle class2 properly if you want all class1 elements to have class2 when the screen width is greater than 768. If you don't want that, just add an extra class that has no effect, but acts as a flag indicating which elements should have class2.



来源:https://stackoverflow.com/questions/20819487/hide-or-remove-a-div-class-at-mobile-viewport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!