Hide A DIV if screen is narrower than 1024px

前端 未结 3 1101
一生所求
一生所求 2020-12-17 01:36

I found (from this question - Hide div if screen is smaller than a certain width) this piece of coding

  $(document).ready(function () {

    if (screen.widt         


        
相关标签:
3条回答
  • 2020-12-17 01:39

    you need to set the screen element:

    var screen = $(window)
    

    for example:

    $(document).ready(function () {
    
        var screen = $(window)    
    
        if (screen.width < 1024) {
            $("#floatdiv").hide();
        }
        else {
    
            $("#floatdiv").show();
        }
    
    });
    
    0 讨论(0)
  • 2020-12-17 01:58

    Media queries for the win

    How do I make a div not display, if the browser window is at a certain width?

    @media all and (max-width: 1024px) { /* Change Width Here */
      div.class_name {
         display: none;
      }
    }
    
    0 讨论(0)
  • 2020-12-17 02:02

    OLD ANSWER USING JQUERY:

    //the function to hide the div
    function hideDiv(){
    
        if ($(window).width() < 1024) {
    
                $("#floatdiv").fadeOut("slow");
    
        }else{
    
            $("#floatdiv").fadeIn("slow");
    
        }
    
    }
    
    //run on document load and on window resize
    $(document).ready(function () {
    
        //on load
        hideDiv();
    
        //on resize
        $(window).resize(function(){
            hideDiv();
        });
    
    });
    

    EDIT: Please note that now there is much more cross browser support for css3 media queries it would be much more effective to use those rather than javascript.

    USING CSS.

    /* always assume on smaller screen first */
    
    #floatdiv {
        display:none;
    }
    
    /* if screen size gets wider than 1024 */
    
    @media screen and (min-width:1024px){
        #floatdiv {
            display:block;
        }
    }
    

    Note that in most modern browsers you can also run media queries in javascript using window.matchMedia

    if(window.matchMedia("(min-width:1024px)").matches){
        console.log("window is greater than 1024px wide");
    }
    
    0 讨论(0)
提交回复
热议问题