使用jquery更改背景图像

时间:2015-03-30 21:18:27

标签: jquery

如何使用jQuery更改背景图片?

它应该更改我的HTML中提供的图像。该函数应该是动态的,可以在调用时更改任何图像。

2 个答案:

答案 0 :(得分:0)

我们假设你有以下代码......



<div id='container'>
  <img src='some location'>
</div>
&#13;
&#13;
&#13;

您可以使用以下jquery代码更改图像...

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

让我知道它是否有效。

答案 1 :(得分: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

指向与代码相关的文档的链接: