Bootstrap change image according to device

前端 未结 4 1934
温柔的废话
温柔的废话 2020-12-14 22:31

I want to show different images in different devices (not background image). Is it possible to do using bootstrap 3.x like the following?

For large screen

         


        
4条回答
  •  鱼传尺愫
    2020-12-14 22:51

    If you want to load only the image relevant to the screen-size, I think the best way is with javascript. Create versions of your photos, and in this case the script looks for an img with "600x400" in the filename, and replaces it with "1200x800" when the screensize is bigger than 767px.

    DEMO: http://www.bootply.com/Y8XECJpGjS#

    Javascript

    if ($(window).width() > 767) {
        $("img[src$='600x400']").each(function() {
            var new_src = $(this).attr("src").replace('600x400', '1200x800'); 
            $(this).attr("src", new_src); 
        });
    }
    

    HTML

    NOTE: this example uses placehold.it images, but obviously you will create your own image versions, include something to identify them in the filename (i.e. 600px, small, v1, etc), and then use that unique string as the find/replace strings in the script. i.e. If your filenames are photo-small.jpg, photo-mediumd.jpg, photo-large.jpg, then the script looks for "small" and replaces with "medium" or "large" where appropriate.

    NOTE: once the image loads, that's it - it does not dynamically change image out as you change the screensize. There is surely a solution that does that, but overkill if not needed.

提交回复
热议问题