2015-03-30 75 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

链接到相关的文档代码: