2014-10-02 83 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