简体   繁体   中英

How do I get multiple image URLs from background CSS attribute?

I have made a small plugin which checks to see if a element(s) background image has loaded.

In doing this I needed to extract the URL of the background image, I have managed to do it when there is just one background image:

var bgURL = $('#myelement').css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '');

However I want to make my plugin support elements with multiple background images

Here is a code pen example of the code in action if it helps.

It would be good if it worked for any css format eg both:

background-image: url(sheep.png), url(betweengrassandsky.png);
background-position: center bottom, left top;
background-repeat: no-repeat;

and

background: url(sheep.png) center bottom no-repeat, url(betweengrassandsky.png) left top no-repeat;

Ideally the result would be an array of the urls (eg 0 => ['sheep.png'], 1 =>['betweengrassandsky.png'])

Thanks in advance guys.

Thanks to artm for his idea.

I split the background image by ", " and then run a foreach loop over the array running my existing replace methods.

This is essentially what I did:

var array = [];
$.each($('#myElement').css('background-image').split(', '), function(key, value){
    array.push(value.replace(/^url\(["']?/, '').replace(/["']?\)$/, ''));
});

Here is a working code pen:

http://codepen.io/catmull/pen/Hhufw

You can download the plugin that detects page load from here as well

http://catmull.uk/code-lab/background-image-loaded/

Obviously you came to the same idea before I can submit, but anyway, I have already written the code... :) Actually, if you use "url" for your split function, you don't have to check if the background has one url or many - idx will be always at least 0 and 1, and you will need to catch always the entries >0.

// Loop through elements
    this.each(function(){
        var Obj = $(this);
        $.each( Obj.css('background-image').split("url"), function(idx, value){
            if (idx>0){
                 //The stuff you're doing with the img tag
                 $('<img/>').attr('src', value.replace( /\(["']?/,'' ).replace( /["']?\),?/,'' )).load(function(){
                     $(this).remove(); // prevent memory leaks
                     settings.afterLoaded.call(Obj);
                 });                }
        });
    });

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