[英]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 我正在尝试拍摄div(缩略图)的背景图像,并将相同的值应用于主图像,以使图像在单击时发生变化
I thought this would work. 我以为这样可以。 I have small divs with the class ProductGalleryThumb and one large image with an id MainImage 我的班级是ProductGalleryThumb,还有一个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... 尝试使用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: 您的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="" />
and here is the jQuery : 这是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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.