2014-11-24 84 views
0

我正在處理用戶輸入筆記本電腦或移動設備的圖像,然後根據src更改的插件。 現在我已經做到了這一點 一個簡單的圖像元素被添加根據屏幕分辨率使用jquery更改網頁上的圖像的src

<img src="#" data-tablet="img/xl.jpg" data-laptop="img/xllaptop.jpg" > 
<img src="#" data-tablet="img/x2.jpg" data-laptop="img/x2laptop.jpg" > 

現在我已經做到了這一點使用JavaScript

var currentWindowSize = $window.width(); 
    if (currentWindowSize <640) 
{ 
     $(img).attr("src","source should come from the data-attribute"); 
    } 
    if (currentWindowSize >640) 
{ 
     $(img).attr("src","source should come from the data-attribute"); 
    } 

現在的問題是它會改變所有圖像的屬性。 我該如何做一些具有相同數據屬性的圖像更改, 我需要它完成而不提供任何Id或類。 謝謝。 來源應該來自數據屬性如數據平板與平板電腦路徑等。 (我可以使用類似這個關鍵字的東西)。 謝謝。

回答

0

試試這個:

var currentWindowSize = $(window).width(); 

if (currentWindowSize <= 640) { 
    $('img').each(
     function(){ 
      $(this).attr("src", $(this).attr("data-tablet")); 

    }); 

} else if (currentWindowSize > 640) { 
    $('img').each(
    function(){ 
     $(this).attr("src", $(this).attr("data-desktop")); 

    }); 
};