Add another background image via jquery

2019-08-19 01:29发布

I would like to add another background image to my div element, however I dont want to simply write over the existing one, I would like to have multiple backgrounds, so it should add the new background url below the first.

Here is the what the original CSS will look like..

#cover-art {
    background:
        url('http://beta.mysite.net/img/banner1.png') top left no-repeat,
    padding:250px 0 0;
}

What I would like to do via jquery is add another image url line below the first one like this...

#cover-art {
    background:
        url('http://beta.mysite.net/img/banner1.png') top left no-repeat,
            url('http://beta.mysite.net/img/banner2.png') top left no-repeat,
    padding:250px 0 0;

}

Also something to note is that #cover-art css is in an external style sheet.

3条回答
Deceive 欺骗
2楼-- · 2019-08-19 01:49

Here you go. Keep in mind this won't work with a lot of browsers that are more than a couple years old:

var _oCurr = jQuery('#cover-art');
var _sBg = _oCurr.css('background-image');
_oCurr.css('background-image', _sBg + ', url(/img/banner2.png)');
查看更多
Ridiculous、
3楼-- · 2019-08-19 01:52

Last I checked, you can't have two background images on 1 element.
CSS3 allows you to do so but it won't work on some browsers. Here's a chart of compatibility.

I suggest you create another element inside #cover-art and apply the same CSS to its child except for the background image.

So for example

<div id="covert-art">
    <div id="child"></div>
</div>

#child's background image would be above the parent (#cover-art)

Check this fiddle as an example.

查看更多
够拽才男人
4楼-- · 2019-08-19 02:10

Try this:

var $el = $('#cover-art');
var bg = $el.css('background-image'); // old image
$el.css('background-image', bg +','+ 'img/banner2.png'); // add new image
查看更多
登录 后发表回答