2017-01-20 27 views
1

HTMLImageElementはというプロパティを持ち、img要素の現在のソースを取得できます。 srcsetで複数のソースを定義する場合に便利です。画像要素の現在の画像ソースを取得

HTMLPictureElementと同等のものはないようです。

picture要素の現在のソースをJavascriptで見つける別の方法はありますか?

+2

ピクチャがピクチャ容器内の画像要素のための異なるソースを提供するためにのみコンテナ要素である - 私は '' img'要素のcurrentSrc'、ここで同じように動作することを前提となります...? – CBroe

+0

@CBroeそれは意味をなさないでしょう、あなたはこれを説明するドキュメントを知っていますか? –

+0

@CBroeあなたは絶対に正しいです。ありがとう! –

答えて

4

あなたは適用された画像を取得するためにpicture要素内img要素のcurrentSrcにアクセスすることができます。

下記のデモ(ブラウザが全画面のデスクトップの場合)のcurrentSrchttp://placehold.it/600x100の画像になります。

window.onload = function() { 
 
    const picture = document.getElementById('pictureEl'); 
 
    const currentSource = document.getElementById('currentSource'); 
 
    currentSource.innerText = picture.getElementsByTagName('img')[0].currentSrc; 
 
}
<picture id="pictureEl"> 
 
<source srcset="http://placehold.it/600x100?text=Source" media="(min-width: 300px)"> 
 
<img src="http://placehold.it/300x100?text=Img"> 
 
</picture> 
 
<div id="currentSource"></div>

+0

スポットあり、ありがとう! –

1

これを使用して画像のソースを取得します。

function getCurrentSrc(element, cb){ 
    var getSrc; 
    if(!window.HTMLPictureElement){ 
     if(window.respimage){ 
      respimage({elements: [element]}); 
     } else if(window.picturefill){ 
      picturefill({elements: [element]}); 
     } 
     cb(element.src); 
     return; 
    } 

    getSrc = function(){ 
     element.removeEventListener('load', getSrc); 
     element.removeEventListener('error', getSrc); 
     cb(element.currentSrc); 
    }; 

    element.addEventListener('load', getSrc); 
    element.addEventListener('error', getSrc); 
    if(element.complete){ 
     getSrc(); 
    } 
} 
+0

'window.respimage'と' window.picturefill'はどこから来たのですか? –

関連する問題