[英]How to make picture element accessible for each breakpoint?
假設您有一個與此類似的圖片元素:
<picture class='my-image'>
<source media="(min-width: 1024px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="med.jpg">
<source srcset="small.jpg">
<img src="small.jpg" alt="">
<p>Accessible text</p>
</picture>
但是假設每個斷點的圖像上下文都不同。 也許在大尺寸的情況下,照片是一個人站在一棵樹前。 但在移動尺寸下,它只是一棵樹的圖片。
有時,某些圖片在移動尺寸下效果很好,而其他圖片則不取決於頁面布局等。
無論如何,對於圖片元素,您只能在一個地方為整個圖片元素指定alt=
屬性。 但是如果圖像上下文在每個斷點之間發生變化,是否有可能以某種方式指定不同的alt=
屬性? 您是否必須為此使用 JavaScript(這可能是屏幕閱讀器友好的,也可能不是)?
用<source>
元素的srcset
替換src
,使用<img>
元素的onerror
事件和window.matchMedia()
來設置alt
屬性。
<script>
function handleError() {
var sources = document.querySelectorAll("picture source");
var img = document.querySelector("picture img");
for (var i = 0; i < sources.length; i++) {
if (window.matchMedia(sources[i].media).matches) {
img.setAttribute("alt", sources[i].dataset.alt);
break;
}
}
}
</script>
<picture class='my-image'>
<source media="(min-width: 1024px)" srcset="large.jpg" data-alt="large">
<source media="(min-width: 768px)" srcset="med.jpg" data-alt="small">
<source srcset="small.jpg" data-alt="small">
<img src="small.jpg" alt="" onerror="handleError()">
<p>Accessible text</p>
</picture>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.