Load images based on screen size

前端 未结 7 1849
臣服心动
臣服心动 2020-12-14 23:23

I have the following HTML code which displays an image:

\"PP\"
7条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 23:47

    I would suggest CSS media query first and then JavaScript if you need to support a browser that doesn't support media query. This example uses 850px as a maximum width before the image is changed.

    CSS:

    /* media query device layout transformation for 850px width trigger */
    #wm01 { 
         background:url(images/large_image.png);
         width:100px;
         height:50px;
    }
    @media screen and (max-width:850px) {
         #wm01 {
             background:url(images/smaller_image.png);
         }
    }
    

    JS/JQuery:

    var width = $(window).width();
    if (width >= 850) {
        $('#wm01').addClass('largeImageClass');
    } else {
        $('#wm01').addClass('smallImageClass');
    }
    

    HTML:

    PP

提交回复
热议问题