图片源未更改图像

时间:2019-03-08 12:41:42

标签: html html5

我创建了一个“图片”元素。在此过程中,我有不同的“源”标签,这些标签根据“媒体”属性的大小和文件类型具有图像。

当我改变屏幕宽度时,图像不会根据屏幕尺寸而改变。

下面是我的代码

<picture class="c-hero_picture">
    <source media="(min-width: 1200px)" type="image/webp" srcset="./img/webp/canada-1600x730.webp 1x, ./img/webp/canada-1920x730.webp 1.2x">
    <source media="(min-width: 1200px)" type="image/jpf" srcset="./img/jpf/canada-1920x730.jpf 1x, ./img/jpf/canada-1920x730.jpf 1.2x">
    <source media="(min-width: 1200px)" type="image/png" srcset="./img/png/canada-1920x730.png 1x, ./img/png/canada-1920x730.png 1.2x">

    <source media="(min-width: 600px)" type="image/webp" srcset="./img/webp/canada-800x730.webp 1x, ./img/webp/canada-1200x730.webp 1.5x, ./img/webp/canada-1600x730.webp 2x">
    <source media="(min-width: 600px)" type="image/jpf" srcset="./img/jpf/canada-800x730.jpf 1x, ./img/jpf/canada-1200x730.jpf 1.5x, ./img/jpf/canada-1600x730.jpf 2x">
    <source media="(min-width: 600px)" type="image/png" srcset="./img/png/canada-800x730.png 1x, ./img/png/canada-1200x730.png 1.5x, ./img/png/canada-1600x730.png 2x">


    <source type="image/webp" srcset="./img/webp/canada-400x730.webp 1x, ./img/webp/canada-600x730.webp 1.5x, ./img/webp/canada-800x730.webp 2x">
    <source type="image/jpf" srcset="./img/jpf/canada-400x730.jpf 1x, ./img/jpf/canada-600x730.jpf 1.5x, ./img/jpf/canada-800x730.jpf 2x">
    <source type="image/png" srcset="./img/png/canada-400x730.png 1x, ./img/png/canada-600x730.png 1.5x, ./img/png/canada-800x730.png 2x">
    <img class="c-hero_img" alt="…" src="./img/png/canada-400x730.png">
</picture>

1 个答案:

答案 0 :(得分:1)

我认为解决此问题的最佳方法是使用CSS样式表

首先,创建您的html。

<img id="picture" src="https://cdn.pixabay.com/photo/2016/11/29/05/55/adult-1867665__180.jpg">

img标签中的源将用于图像

然后,您将需要定义图像的ID,例如

#picture {
    width: 100%;
    height: 100%;
}

然后使用媒体规则,例如

@media screen and (min-width: 600px) {
    #picture {
        content: url(https://cdn.pixabay.com/photo/2016/05/05/02/37/sunset-1373171__180.jpg);
  }
}

因此,您的最终版本应该是这样的:

#picture {
  width: 100%;
  height: 100%;
}

@media screen and (min-width: 600px) {
  #picture {
    content: url(https://cdn.pixabay.com/photo/2016/05/05/02/37/sunset-1373171__180.jpg);
  }
}

@media (min-width: 1200px) {
  #picture {
    content: url(https://images.pexels.com/photos/1830569/pexels-photo-1830569.jpeg);
  }
}
<!DOCTYPE html>
<html>

<head>
  <title>answer</title>
</head>

<body>
  <img id="picture" src="https://cdn.pixabay.com/photo/2016/11/29/05/55/adult-1867665__180.jpg">
</body>

</html>