开发者

Dynamic CSS Sprite Injection

So the title of this question may be a bit ambiguous, so I'm going to try and explain it as simply as possible.

I have created a dynamic image sprite control in .NET to take any number of images and convert them into an image sprite. For example:

Image 1 = /images/img1.jpg
Image 2 = /images/img2.jpg
Image 3 - /images/img3.jpg

.NET then takes those images and by using a url creates a sprite on the server and returns back as one image (sprite):

/DynamicSprite.ashx/?image=/images/img1.jpg&image=/images/img2.jpg&image=/images/img3.jpg

I am using XML and jQuery to find the source of all of the images and inject them to into the url string.

My question is how to make this dynamic in js, so that no matter how many images I have, js would create the sprite url string I need on the fly.

So, if there's 7 images, the url above would have 7 image urls injected into it to create my image sprite.

A rough jQuery example to help along:

var imageSrc = $('div a');    
var imageArray = ['image1', 'image2', 'image3', 'image4', 'image5', 'image6' , 'image7'];
imageSrc.css('background', 'url(\'/DynamicSprite.ashx/\')');

What would go here: 'url(\'/Dynam开发者_StackOverflow社区icSprite.ashx/\')' so that the ?image= and &image= strings are populated based on how many items there are in the array and how to get that info using an index rather than manually setting the positions, i.e.: imageArray[0]


i think i understand what you want but im not sure. so here is a way to make an array of image src's and then output a background url from them

//the element to add the bg to
var imgSrc = $("div a");

//the elements to loop through
var imgLoop = $("img");

//create our array
var srcArray = new Array();

//loop through the elements
imgLoop.each(function(i){

    //grab the src of the elements
    var src = $(this).attr("src");

    //put the src into our array
    srcArray[i] = "image="+src+"&";

});

//collapse the array to a string
var images = srcArray.join("");

//set the bg image url
var bgUrl = "DynamicSprite.ashx?"+images;

//add the background
imgSrc.css("background","url("+bgUrl+")");

Hope this helps. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜