简体   繁体   中英

Different Image Size Desktop & Mobile

I just did a speed test on desktop & mobile on gtmetrix and have the error code: Serve Scaled Images - But only on the mobile speed test. The error reads as follows:

* * .jpg is resized in HTML or CSS from 1200x431 to 318x114. Serving a scaled image could save 520.9KiB (92% reduction).

Is there a specific code I can put with the image to have it one size when on mobile and leave the desktop one at the original/other size. Or is there another way such as serve a particular image for mobile (same image smaller size) then another image for serving desktops?

Thanks.

You can do like this and define different background url on different media queries for same class.

    /* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}

I think you might want something like this:

    var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

if(isMobile.any()){
    // Mobile!
} else {
    // Not mobile
}

You can then do something like: (untested below(needs tweaking))

if(isMobile.any()){
img { height:140%;width:140%

You can alter the size of images through the style tag. img { should alter all <img src tags on the page as I've done it before. And a revision of the above code should alter it only for mobile or desktop computers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM