html 加载背景图片质量较低

html load background image lower quality

我有一个网站代码:

#part1{
    background-image: url('grass_v001.png');
}

但是,grass_v001.png 是一个非常大的文件,在浏览器上加载需要花费过多的秒数(加载时间慢 = 外观不够专业)。有没有办法仅通过 css 来降低图像质量?为此,我宁愿不使用 JS 或 Jquery,但如果需要,我会的。谢谢!

您可以仅使用 HTML 和 CSS 按比例缩放图像,但浏览器仍会将整个图像加载到内存中。

您需要使用一些照片编辑软件将图像的分辨率和图像格式更改为 JPEG,它具有比 PNG 图像格式更好的压缩算法。

HTML:

<div class="img_resz">
    <img src="img.jpg">
</div>

CSS:

.img_resz img 
{
    width: 90%;
}

对于CSS,可以用image-set来处理

创建几个较小版本的图像,并在图像集中提供它们 - 然后让浏览器选择合适的图像。这样,可以很好地利用高分辨率的大屏幕将得到服务,而小屏幕可以使用速度更快、分辨率较低的图像。

The image-set() CSS functional notation is a method of letting the browser pick the most appropriate CSS image from a given set, primarily for high pixel density screens.

Resolution and bandwidth differ by device and network access. The image-set() function delivers the most appropriate image resolution for a user's device, providing a set of image options — each with an associated resolution declaration — from which the browser picks the most appropriate for the device and settings. Resolution can be used as a proxy for filesize — a user agent on a slow mobile connection with a high-resolution screen may prefer to receive lower-resolution images rather than waiting for a higher resolution image to load.

image-set() allows the author to provide options rather than determining what each individual user needs.

例子

#part1 {
    background-image: image-set(
        url('grass_v001_small.png') 1x,
        url('grass_v001_large.png') 2x
    );    
}

您还需要为某些浏览器添加重复的“-webkit-”供应商前缀(您应该考虑 CSS processors 来为您处理)。

#part1 {
        background-image: image-set(
            url('grass_v001_small.png') 1x,
            url('grass_v001_large.png') 2x
        );
        background-image: -webkit-image-set(
            url('grass_v001_small.png') 1x,
            url('grass_v001_large.png') 2x
        );    
    }