2011-05-23 37 views
0

我使用圖片精靈畫廊。爲了得到正確的背景圖片在正確的地方,我用這個:自動精靈計算 - CSS3或Jquery?

<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> 

這是一種耗時數當有許多div標籤的所有背景值,並在添加的數量例如爲73px,而不是200 。它也佔用了大量的css代碼。

我可以以另一種方式使用CSS3實現相同的結果嗎?

否則我不知道是否有人能有我的jQuery腳本看看,看看是否有東西,可以以更好的方式(腳本作品)來完成:

<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> 

回答

1

我沒有有一個背景圖像的工作,但這裏是一個使用函數傳遞給CSS來修改元素的高度的例子。你想要做的只是將height屬性換成backgroundPosition之一,並將返回值切換爲負值。

這應該大幅減少你的代碼。

$(function() { 
    $("#container div").css('height', function(i, oldValue) { 
     return (i+1)*200; 
    }).fadeIn(400); 
}); 

The proof is in the fiddle.

如果你希望修改多個CSS屬性,你需要使用地圖或者部分列出的.CSS例如頁面上的其他方法:http://api.jquery.com/css/

哦,作爲一個附註,從來沒有明確檢測到這樣的瀏覽器。你想做功能檢測,因爲我敢打賭你的代碼打破IE9,假設IE9現在處理的背景定位不同於IE8。 http://www.jibbering.com/faq/notes/detect-browser/

+0

謝謝Adam!將再玩一些,並拿回我的最終結果。 – Hakan 2011-05-23 13:50:43

+0

如果我的回答有幫助,請將其投票和/或標記爲答案!祝你好運。 – 2011-05-23 16:03:37