【问题标题】:Html5 Picture elementHtml5 图片元素
【发布时间】:2019-09-06 22:33:06
【问题描述】:

我有以下代码,用于图片库,但无法使其工作:

<picture>
  <source srcset="/web/gallery/17/1567772625.webp" type="image/webp"> 
  <source srcset="/web/gallery/17/1567772625.jpg" type="image/jpg"> 
  <source srcset="/web/gallery/17/1567772625-thumb.webp" type="image/webp"> 
  <source srcset="/web/gallery/17/1567772625-thumb.jpg" type="image/jpg"> 
  <a class="mg-image-wrap" data-title="Snaps From The Resort" href="/web/gallery/17/1567772625.jpg">
    <img alt="Snaps From The Resort" class="mg-image" data-position="0" src="/web/gallery/17/1567772625-thumb.jpg" />
  </a>                                             
</picture>

但是,如果我将代码更改为以下内容:

<picture>
  <source srcset="/web/gallery/17/1567772625-thumb.webp" type="image/webp"> 
  <source srcset="/web/gallery/17/1567772625-thumb.jpg" type="image/jpg"> 
  <img  src="/web/gallery/17/1567772625-thumb.jpg" />
</picture>

我有两个问题:

  1. 如何使第一个块下载 webp,在支持的情况下,特别是缩略图下载为 jpg?
  2. 如何防止用户点击href链接才下载href图片?

【问题讨论】:

    标签: html css webp srcset


    【解决方案1】:

    图片元素

    嗯,首先,只有&lt;source&gt;&lt;img&gt; elements are allowed INSIDE &lt;picture&gt;。这意味着如果希望它链接到某个地方,您应该将图片包装在锚标记中或在图片上使用 javascript 点击处理程序。

    <a href="#">
      <picture>...</picture>
    </a>
    

    使用 Webp

    您应该将&lt;picture&gt; 视为具有多个属性的单个元素,就像任何其他图像一样。这意味着缩略图和画廊图像是分开的,并使用 JS 来交互/更改“可见”图像。

    基本上,浏览器会抓取与其功能匹配的第一张图片。 (这就是 img 标签在最后的原因)

    您可以使用media-queriespicture 元素内指定不同大小的图像,但这些图像旨在根据布局大小加载不同的图像,而不是针对不同的交互/用例

    例子:

    <picture>
        <source srcset="imageOne.jpg" type="image/jpg" media="(min-width: 1400px)">
        <source srcset="mediumImg.jpg" type="image/jpg" media="(min-width: 800px)">
        <source srcset="smallImg.jpg" type="image/jpg" media="(min-width: 400px)">  
        <img  src="fallback.jpg" />
    </picture>
    

    这会导致设备根据设备宽度加载不同的图片...


    您也可以像添加任何其他图像一样直接在图片标签上添加任何additional attributes

    <picture class="mg-image" data-position="0" >
       ...
    </picture>
    

    【讨论】:

    • 嗨,布莱斯,感谢您的回答,但这并不能解决我面临的问题。像&lt;a href=''&gt; 也是一个图像链接,我如何使用相同的&lt;picture 元素呢?
    • 锚标签不能在图片元素内。将图片放在锚点内。
    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 2017-10-12
    • 2015-03-16
    • 2017-01-07
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    相关资源
    最近更新 更多