Automatic sprite calculation - CSS3 or Jquery?
I use image sprites for my gallery. To get the right background image in the right place I use this:
<style>
#container div:nth-child(1){background-position:0 0}
#container div:nth-child(2){background-position:200px 0}
#container div:nth-child(3){background-position:400px 0}
#container div:nth-child(4){background-position:600px 0}
#container div:nth-child(5){background-position:800px 0}
#container div:nth-child(6){background-position:1000px 0}
</style>
It's kind of time consuming to count all background values when there are many div tags and when th开发者_高级运维e number to add is for example 73px instead of 200. Also it takes up lots of css code.
Can I achieve the same result in another way using CSS3?
Otherwise I wonder if someone could have a look on my jquery script, to see if there is something that can be done in a better way (the script works):
<div id="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(function() {
$("#container div:first-child").fadeIn(400, showNext);
});
function showNext() {
var test1 = $(this).index(),
test2 = test1*200;
if (navigator.appName=='Microsoft Internet Explorer'){
$(this).css('backgroundPositionX', -test2);
}
else{
$(this).css('backgroundPosition', -test2);
}
$(this).next().fadeIn(400, showNext);
}
</script>
I didn't have a background image to work off of, but here's an example of using a function passed to CSS to modify the height of an element. What you want to do is just swap out the height
property with your backgroundPosition
one, and switch the return value to be negative.
This should substantially minimize your code.
$(function() {
$("#container div").css('height', function(i, oldValue) {
return (i+1)*200;
}).fadeIn(400);
});
The proof is in the fiddle.
If you're looking to modify more than one CSS property, you'll want to use map or some of the other methods outlined on the .CSS example page: http://api.jquery.com/css/
Oh, and as a side note, never explicitly detect a browser like that. You want to do feature detection, since I bet your code breaks IE9, assuming IE9 handles background positioning differently now than IE8. http://www.jibbering.com/faq/notes/detect-browser/
精彩评论