2014-11-24 62 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")); 

    }); 
};