简体   繁体   English

使用图片标签加载图像

[英]load images using the picture tag

I currently try to use the picture tag for a website.我目前尝试为网站使用图片标签。 This is my current code (the picture are at /images/test1.jpg and /images/test2.jpg:这是我当前的代码(图片位于 /images/test1.jpg 和 /images/test2.jpg:

<picture>
  <source srcset="/images/test2.jpg" type="image/jpeg" >
  <img src="/images/test1.jpg">
</picture>

The expected result is that when the browser supports it it loads the image from the srcset and otherwise from the img tag.预期的结果是,当浏览器支持它时,它会从 srcset 加载图像,否则从 img 标签加载。 However I tested in Chrome and Firefox, which should both support it and the result is that it shows the image from the srcset with a size of 0x0 and additionally shows the picture from the src tag.但是我在 Chrome 和 Firefox 中进行了测试,它们应该都支持它,结果是它显示了 srcset 中大小为 0x0 的图像,并另外显示了来自 src 标签的图片。 How to correctly implement this using the picture tag?如何使用图片标签正确实现这一点?

Edit: this is how I added the class defining the image width earlier, which resulted in a empty field of the width I set in the image class and a field with the image from the src.编辑:这就是我之前添加定义图像宽度的类的方式,这导致了我在图像类中设置的宽度的空字段和带有来自 src 的图像的字段。

<picture>
  <source class="image" srcset="/images/test2.jpg" type="image/jpeg" >
  <img class="image" src="/images/test1.jpg">
</picture>

I don't clearly understand what is the goal here.我不清楚这里的目标是什么。 But you missed the media attribute.但是您错过了媒体属性。 The last fallback only works when there are no media around.最后一个回退仅在周围没有媒体时才有效。

<picture>
  <source class="image" srcset="images/test2.jpg" type="image/jpeg" media="(min-width: 1900px)">
  <img class="image" src="images/test1.jpg">
</picture>

thanks for all the help.感谢所有的帮助。 I found my issue: Actually I screwed up two things我发现了我的问题:其实我搞砸了两件事

  1. I did not really get that I always get the image from the src tag我并没有真正明白我总是从 src 标签中获取图像
  2. I should not set the class for both source tag and the img tag, but only for the img tag我不应该为 source 标签和 img 标签设置类,而应该只为 img 标签

this solution works这个解决方案有效

<picture>
  <source srcset="/images/test2.jpg" type="image/jpeg" >
  <img class="image" src="/images/test1.jpg">
</picture>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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