0

ギャラリーに画像スプライトを使用しています。適切な場所に適切な背景画像を取得するには、これを使用します。

<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 タグがあり、追加する数がたとえば 200 ではなく 73px の場合、すべての背景値をカウントするのに時間がかかります。また、大量の 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>
4

1 に答える 1

1

作業する背景画像はありませんでしたが、CSS に渡された関数を使用して要素の高さを変更する例を次に示します。あなたがしたいことは、heightプロパティを自分のbackgroundPositionものと交換し、戻り値を負に切り替えることです。

これにより、コードが大幅に最小化されます。

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

証拠はフィドルにあります。

複数の CSS プロパティを変更する場合は、map または .CSS のサンプル ページ ( http://api.jquery.com/css/ ) で概説されているその他のメソッドを使用することをお勧めします。

ああ、補足として、そのようなブラウザを明示的に検出しないでください。IE9がIE8とは異なる方法で背景の位置を処理すると仮定すると、コードがIE9を壊すに違いないので、 機能検出を行いたいと思います。http://www.jibbering.com/faq/notes/detect-browser/

于 2011-05-23T12:49:39.550 に答える