2015-07-12 52 views
0

我有被放置由外部腳本的圖像:頁面加載後交換(替換)圖像src?

<img src="https://example1.com/image1.png" id="image1"> 

我需要交換(替換)圖片src與我的形象,

原始腳本加載後。

我找到了通過單擊或鼠標懸停來更改圖像src或更復雜的圖像集的解決方案,但是我可以在頁面加載時爲單個圖像強制進行圖像交換而無需額外操作嗎? 在此先感謝您的建議。

+0

這種或那種方式,你需要能夠告訴這個時候其他腳本放在圖像;我們沒有足夠的信息來知道這個腳本函數是發生在「在頁面加載」,「在文檔加載」,「在圖書館加載」等等。檢查有問題的腳本以查看它是否提供「在加載」或「就緒「回調參數。 – Katana314

+0

謝謝你的回覆。我不知道如何檢查這個。有沒有方法來嘗試圖像src替換,看看它是否工作? – carpeperdiem

回答

1

如果我得到你的權利,你要執行的頁面加載的變化:

$(function() { 
    $("#image1").attr("src", "https://example2.com/image2.png") 
}) 
+0

這工作完美。謝謝! – carpeperdiem

0

在這裏你去,

$(function(){ 
     $('#image1').attr('src', $('#image2').attr('src')); 
    }) 

說明:

$('#image2').attr('src')將返回src您的圖片屬性存在於img id=image2中,並且src將被設置在src中的img id=image1

,這將被自動觸發,因爲jQuery確保ttribute,

$(function(){ 
    //wherever you write here will be executed only after DOM load, no external trigger needed 
}) 

希望它能幫助:)

+0

謝謝你分享這個。我從這裏的每個人都學到了很多! – carpeperdiem

+0

@carpeperdiem,如果你喜歡,你可以隨時通過提高我的答案來感謝我:D –

1

你需要這樣做的window.load事件。

  1. 如果要交換它DOM加載後:

$(document).ready(function() { 
 
    $('#image1').attr('src', 'http://placehold.it/150x350'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img src="http://placehold.it/350x150" id="image1">

  • 如果要後替換它原始圖像將被加載
  • 有時要操縱的照片,並用$(文件)。就緒() 你將不能夠這樣做,如果遊客沒有圖像 已經加載。在這種情況下,您需要在圖像加載完成時初始化jQuery 對齊函數。

    但它是無用的。用戶幾乎看不到原始圖像(它將很快交換)。

    $(window).load(function() { 
     
        $('#image1').attr('src', 'http://placehold.it/150x350'); 
     
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
     
    <img src="http://placehold.it/350x150" id="image1">

    http://www.sitepoint.com/types-document-ready/

    +0

    謝謝你分享這個。我從這裏的每個人都學到了很多! – carpeperdiem

    0

    如果你想快速改變圖像儘可能可以使用DOMNodeInserted事件。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
     
        <body> 
     
         <script> 
     
          // Swap out the image as soon as the DOM is inserted 
     
          $('body').on('DOMNodeInserted', '#image1', function(e) { 
     
           $("#image1").attr("src", "http://placehold.it/100x100").attr("id", "image2"); 
     
          }); 
     
         </script> 
     
         
     
         <div id="js-putImageHere"></div> 
     
         
     
         <script> 
     
          // Here is the external code that loads the image you don't want 
     
          $("#js-putImageHere").html('<img src="http://placehold.it/350x150" id="image1">'); 
     
         </script> 
     
        </body>

    +0

    謝謝你分享這個。我從這裏的每個人都學到了很多! – carpeperdiem