Changing a class name with jquery given a specific width range (media query)

前端 未结 3 894
一个人的身影
一个人的身影 2020-12-30 10:49

I have the following html that I am trying to modify:

I

相关标签:
3条回答
  • 2020-12-30 10:55

    You can do something like:

    var x = $('#myelement'); // this is your element
    var w = $(window).width();
    if(w >= 700 && w <= 900) {
        x.removeClass('class-to-remove').addClass('class-to-add');
    }
    
    0 讨论(0)
  • 2020-12-30 11:03

    Take a look at enquire.js

    It is a no dependency library that allows you to respond to media queries with JavaScript.

    For example:

    var $info = $('#info');
    
    enquire.register("screen and (min-width: 1240px) and (max-width: 1484px)", {
        match: function() {
            $info.addClass('col8');
        },
    
        unmatch: function() {
            $info.removeClass('col8');
        }
    }).listen();
    

    Then you can simply register media queries for the various breakpoints in your site so classes will be added and removed upon successful match.

    0 讨论(0)
  • 2020-12-30 11:21

    You can try this.

    $(window).resize(function(){
       console.log('resize called');
       var width = $(window).width();
       if(width >= 700 && width <= 900){
           $('#myelement').removeClass('width8').addClass('width6');
       }
       else{
           $('#myelement').removeClass('width6').addClass('width8');
       }
    })
    .resize();//trigger the resize event on page load.
    
    0 讨论(0)
提交回复
热议问题