Javascript 如何获取div的背景图像值并将其应用于img标记onclick的src值?

Javascript 如何获取div的背景图像值并将其应用于img标记onclick的src值?,javascript,jquery,image,onclick,Javascript,Jquery,Image,Onclick,我正在尝试获取div(缩略图)的背景图像,并将相同的值应用于主图像,以便图像在单击时更改 我想这会管用的。我有ProductGalleryThumb类的小div和一个id为MainImage的大图像 $('.ProductGalleryThumb').click(function () { var i = $(this).css('background-image', 'url(' + $(this).attr('rel') + ')'); $("#MainImage").htm

我正在尝试获取div(缩略图)的背景图像,并将相同的值应用于主图像,以便图像在单击时更改

我想这会管用的。我有ProductGalleryThumb类的小div和一个id为MainImage的大图像

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

非常感谢您一如既往的帮助。

您的HTML应该如下所示:

<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="" />

您的HTML应该如下所示:

<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="" />

尝试使用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 + '" />');
});
$('.ProductGalleryThumb')。单击(函数(){
//获取计算样式
var style=this.currentStyle | | window.getComputedStyle(this,false);
//img src位于“url(+)”内-将它们切掉
var src=style.backgroundImage.slice(4,-1);
$(“#main image”).html(“”);
});

尝试使用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 + '" />');
});
$('.ProductGalleryThumb')。单击(函数(){
//获取计算样式
var style=this.currentStyle | | window.getComputedStyle(this,false);
//img src位于“url(+)”内-将它们切掉
var src=style.backgroundImage.slice(4,-1);
$(“#main image”).html(“”);
});

一个ID只能属于一个元素。如果不是这样,请使用类。谢谢,我确实知道这一点,但在陷入其中时忽略了它,我相应地更改了代码:)一个ID只能属于一个元素。如果不是这样,请使用类。谢谢,我确实知道这一点,但在陷入其中时忽略了这一点,我相应地修改了代码:)完全有道理,当您看到这样的情况时非常明显,非常感谢您的帮助。立即解决了我的问题:)@KarlHumphries没有问题,是的,如果你知道jQuery的基本知识,我想这是不言自明的:)完全有道理,当你这样看的时候,这是显而易见的,非常感谢你的帮助。立即解决了我的问题:)@KarlHumphries没有问题,是的,如果你知道jQuery的基本知识,我想这是很自然的:)我必须说这是一个非常好的选择。我必须说这是一个非常好的选择。