2015-03-30 77 views
0

如何使用jQuery更改背景圖片?更改背景使用jquery點擊圖片

它應該改變我的HTML提供的圖像。該函數應該是動態的,以便在調用時更改任何圖像。

+0

我清理你的問題有點。你試過什麼了?任何我們可以離開的地方? – Celeo 2015-03-30 22:14:04

回答

0

比方說,你有下面的代碼...

<div id='container'> 
 
    <img src='some location'> 
 
</div>

您可以用下面的jQuery代碼改變形象...

function change_image(){ 
 
    
 
    $("#container").html("<img src='some other image location'>"); 
 
    
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

讓我知道它是否有效。

0

因爲你說你是jQuery的新手,所以我在註釋代碼時特別注意。你沒有真正指定背景圖像應該如何設置,所以我在縮略圖上使用了一個點擊事件。

代碼:

// before doing our magic with jQuery, 
// we must wait for the dom to be ready to be manipulated 
$(document).ready(function() { 

    // listen for a click on any img inside the .images 
    $('.images img').on('click', function() { 

     // inside the event handlers callback, THIS refers to the img that was clicked 
     // here we save the src property of the clicked img to a variable 
     var imgSrc = $(this).prop('src'); 

     changeBackgroundImg(imgSrc); 
    }); 

}); 

function changeBackgroundImg(imgSrc) { 
    // we can set any css property to an element with jQuerys .css() 
    $('body').css('background-image', 'url(' + imgSrc + ')'); 
} 

這裏有一個demo

鏈接到相關的文檔代碼: