how to specify a different image in css depending if the user visits on a desktop or a mobile browser

前端 未结 3 1783
盖世英雄少女心
盖世英雄少女心 2020-12-31 12:44

Just a question about css for mobile devices,

i have an image that is 1260px wide on my website and when i look at it on the phone it destorts the website as the res

相关标签:
3条回答
  • 2020-12-31 13:29

    Im not sure if you want JS, i decided to answer your question if you want CSS3, try this:

    HTML:

    <img src="image.jpg"
         data-src-960px="image-960px.jpg"
         data-src-1260px="image-1260px.jpg"
         alt="">
    

    CSS:

     @media (min-device-width:320px) {
            img[data-src-960px] {
                content: attr(data-src-960px, url);
            }
        }
    
        @media (min-device-width:960px) {
            img[data-src-1260px] {
                content: attr(data-src-1260px, url);
            }
        }
    

    jQuery version:

     $(document).ready(function() {
    
     function imageresize() {
     var contentwidth = $('#content').width();
     if ((contentwidth) < '960'){
     $('.imageclass').attr('src','image-960px.jpg');
     } else {
     $('.imageclass').attr('src','image-1260px.jpg');
     }
     }
    
     imageresize();//Activates when document first loads    
    
     $(window).bind("resize", function(){
     imageresize();
     });
    
     });
    
    0 讨论(0)
  • 2020-12-31 13:41

    Inspired by Ivan's answer, here is a jQuery version that uses media queries to be as close as possible to his CSS3 solution (which doesn't work for me in Firefox 31 and Safari 7):

    $(document).ready(function() {
        var mqsmall = "(min-device-width:320px)";
        var mqbig   = "(min-device-width:960px)";
        function imageresize() {
            if(window.matchMedia(mqbig).matches) {
                $('img[data-src-1260px]').each(function () {
                    $(this).attr('src',$(this).attr('data-src-1260px'));
                });
            }
            else if(window.matchMedia(mqsmall).matches) {
                $('img[data-src-960px]').each(function () {
                    $(this).attr('src',$(this).attr('data-src-960px'));
                });
            }
        }
    
        imageresize();
    
        $(window).bind("resize", function() {
            imageresize();
        });
    });
    
    0 讨论(0)
  • 2020-12-31 13:44

    You're looking for media queries. You can write styles conditional on width:

    http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

    http://www.w3.org/TR/css3-mediaqueries/

    0 讨论(0)
提交回复
热议问题