简体   繁体   English

使用jQuery更改div中的特定背景图像

[英]Change SPECIFIC background image in div with jquery

I have a div which has more than one image set as a background. 我有一个div,其中有多个图像设置为背景。

background-image: 
       url(/Content/frontend/images/left.png), 
       url(/Content/frontend/images/right.png), 
       url(http://IMAGE_I_WANT_TO_TARGET),
       linear-gradient($dark 0%, $light 100%);

If i target my div and change the background image, it overwrites all other images: 如果我将div作为目标并更改背景图像,它将覆盖所有其他图像:

$(".div").css("background-image", "url(http://placehold.it/300?text=asdasd)");

Is it possible to target just the 3rd image and change it? 是否可以仅将第三个图像作为目标并进行更改?

Try this, Suppose you have 3 background images in your div. 尝试此操作,假设您的div中有3个背景图像。

var images = $('.div').css('background-image'); // get all background images
var i = images.split(',');
var imageArray = [];
imageArray = imageArray.concat(i);
imageArray[2] = 'url(4th-image.jpg)'; // set your new image
$('.div').css('background-image',imageArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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