简体   繁体   中英

How can I get the background-image value of a div and apply it to the src value of an img tag onclick?

I am trying to take the background image of my div (thumbnail) and apply the same value to the main image so that the image changes onclick

I thought this would work. I have small divs with the class ProductGalleryThumb and one large image with an id MainImage

$('.ProductGalleryThumb').click(function () {
    var i = $(this).css('background-image', 'url(' + $(this).attr('rel') + ')');
    $("#MainImage").html('<img src="' + i + '" />');
})

Any help much appreciated as always.

Try using window.getComputedStyle...

$('.ProductGalleryThumb').click(function () {

    // get computed style
    var style = this.currentStyle || window.getComputedStyle(this, false);

    // img src is inside 'url(' + ')' - slice those off
    var src = style.backgroundImage.slice(4, -1);

    $("#MainImage").html('<img src="' + src + '" />');
});

Your HTML should look something like this:

<div class="ProductGalleryThumb" style="background-image:url(img1.jpg)"></div>
<div class="ProductGalleryThumb" style="background-image:url(img2.jpg)"></div>
<div class="ProductGalleryThumb" style="background-image:url(img3.jpg)"></div>

<img id="MainImage" src="" alt="" />

and here is the jQuery :

$('.ProductGalleryThumb').click(function () {
    var image = $(this).css('background-image');
    // remove "url(" and ")" to get the url
    image = image.replace('url(','').replace(')','');
    $("#MainImage").attr('src',image);
});

JS Fiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM