开发者

Changing background image with jquery

I will have a list of images (tiled background type) I would like to be able to click on an image and make it the background image for the entire body for display purposes. so far I have this:

$(document).ready(function(){       

    //var image = ???; what should be here?

    $('.img1').click(function(){
        $('#body').css('background-image', 'url(images/tiles/tile77.jpg'); //the image url cannot be one single url
        });   

    });   

my开发者_如何学编程 current row of images(just being used to get the script working. The images will be coming from a database later.

<div class="threecol"><img class="img1" src="images/tiles/tile39.jpg"></div>
<div class="threecol"><img class="img1" src="images/tiles/tile77.jpg"></div>
<div class="threecol"><img class="img1" src="images/tiles/tile47.jpg"></div>
<div class="threecol last"><img class="img1" src="images/tiles/tile33.jpg"></div>

The script works the way I have it, but I need the background image to be the image that I clicked on, not the static one I have here. I need it to work each time I click on an image.

I admit it, I am clueless as to how to get it to work time after time and also how to configure the script at .css(background-image, ?????) to be dynamic

Thanks for any advice


Grab the src attribute of the .img1 element you just fired the click event on and set that as the URL in your CSS modification to the body element:

$('.img1').click(function(){
    $('body').css('background-image', 'url(' + this.src + ')');
});

Also there should only ever be a single body element in your document, so no need to select it via an ID, just use $('body') instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜