2014-10-02 55 views
1

我有一些jquery,它会在屏幕尺寸低于600像素时替换图像。jquery图像替换屏幕尺寸调整

<script type="text/javascript"> 
    jQuery(window).on("load resize", function (e) { 
     jQuery(function() { 
      if (jQuery(window).width() <= 600) { 
       jQuery("img").each(function() { 
        jQuery(this).attr("src", jQuery(this).attr("src").replace("img/my_safe_net_hero_img_knight_2014_2.jpg", "img/my_safe_net_knight_mob_version_2014.png")); 
       }); 
      } 

     }); 
    }); 
</script> 

这是有效的,但是如果你想再次放大屏幕,小图仍然存在。我想我可以通过添加一个else语句来修复它,但它不起作用。当我这样做的时候,似乎打破了整个事情。

<!--Hero Image Replacement--> 
<script type="text/javascript"> 
    jQuery(window).on("load resize", function (e) { 
     jQuery(function() { 
      if (jQuery(window).width() <= 600) { 
       jQuery("img").each(function() { 
        jQuery(this).attr("src", jQuery(this).attr("src").replace("img/my_safe_net_hero_img_knight_2014_2.jpg", "img/my_safe_net_knight_mob_version_2014.png")); 
       }); 
      } 
      else { 
       jQuery(this).attr("src", jQuery(this).attr("src").replace("img/my_safe_net_knight_mob_version_2014.png" , "img/my_safe_net_hero_img_knight_2014_2.jpg")); 
      }; 
     }); 
    }); 
</script> 

上面的脚本有什么问题。我应该使用不同的东西来达到这个目的吗?

这里是一个Fiddle of my code

+0

在其他方面,你没有循环使用'img'。 – 2014-10-02 14:13:33

回答

1

试试这个:

http://jsfiddle.net/kgnfqbxs/1/

jQuery(window).on("load resize", function (e) { 
      if (jQuery(window).width() <= 600) { 
       jQuery("img").each(function() { 
        jQuery(this).attr("src", jQuery(this).attr("src").replace("http://placehold.it/350x150", "http://placehold.it/150x150")); 
       }); 
      } else { 
       jQuery("img").each(function() { 
        jQuery(this).attr("src", jQuery(this).attr("src").replace("http://placehold.it/150x150", "http://placehold.it/350x150")); 
       }); 
      } 

    }); 

请考虑,这将不必要地循环在你的页面每一个形象,有更好的方式,如果可以的话,像给你的图像一个ID =“myimage”,然后只是:

jQuery("#myimage").attr("src","http://placehold.it/150x150"); 

jQuery("#myimage").attr("src","http://placehold.it/350x150"); 
+0

对不起,我不太明白你说什么会'循环'页面中的每个图像的含义。你能澄清一下吗? – onTheInternet 2014-10-02 14:29:23

+0

@onTheternet jQuery(“img”)。each(..)表示非常标记在页面中执行此操作(替换文本)。这使得脚本可以查看页面的每个标签来查找图像,因此在大型网站上这不是一个好方法。但如果网站很小,那对你来说可能会很好。第二种方法更快更干净,但您需要在HTML – FrancescoMM 2014-10-02 14:45:17

+0

中放置一个id =“my_image”谢谢,这样做很有意义 – onTheInternet 2014-10-02 14:56:35