私はあなたがすべてのピースを持っていると信じています、あなたはそれらをまとめる必要があるだけなので、これを分解しましょう。
現在表示されている画像を追跡し、各画像の高さがわかっている場合、適切な背景位置を計算するのは非常に簡単です。あなたの追跡変数をと呼んでいるとしましょうi
。i
これが機能するには、ゼロベースである必要があることに注意してください。各画像の高さは100pxと想定しています。また、必要な負の値を取得するために乗算し-1
ます。
var position = "0 " + (i * 100 * -1) + "px"; // Will be something like "0 -100px"
jQueryの次の.css()
ようなものを使用して、background-positionを変更できます。
$("#your-image-container-id").css("backgroundPosition", position);
jQueryを使用して、ボタンのクリックイベントリスナーを追加できます.click()
。
$("#your-button").click(function () {
/*
Do your rotation magic here
For the next button increase i by one and apply the new position
For the prev button you decrease i by one instead...
*/
});
これらの要素があれば、必要なコードを組み立てることができるはずです。どこかで行き詰まったら、お気軽にお問い合わせください。
アップデート:
私はあなたのためにいくつかの部品を組み立てました:
$(function () {
var i = 0,
numberOfImages = 5;
// Handle click on next button
$(".next-btn").click(function () {
// Increase by one, and restart when we reach the last image
i = ((i + 1) < numberOfImages) ? i + 1 : 0;
var position = calculateBackgroundPosition(i);
$(".image-container").css("backgroundPosition", position);
});
});
function calculateBackgroundPosition(index)
{
return "0 " + (index * 100 * -1) + "px";
}
このフィドルでも利用できます。まだやるべきことは前のボタンを実装することですが、それはあなたの仕事になります。次のボタンがどのように実装されているかを見てから、試してみてください。
アップデート2:
Firefoxで背景位置をアニメーション化するのは少し面倒なようです。Firefoxで正しく動作させるための拡張機能を説明するこのSOの回答を見つけました。残念ながら、Firefoxはをサポートしておらずbackground-position-y
、前述の拡張機能はjQueryのbackgroundPosition: "+=50px"
構文をサポートしていません。そのため、回避策を実行する必要がありました。
それほどスムーズではありませんが、上記の拡張機能を含めると。次のコードで動作させることができます。
$(function () {
var i = 0,
numberOfImages = 5;
$(".op").click(function () {
// Decrease by one, and restart when we reach the first image
i = ((i - 1) >= 0) ? i - 1 : numberOfImages - 1;
animate(this, i);
});
$(".ned").click(function () {
// Increase by one, and restart when we reach the last image
i = ((i + 1) < numberOfImages) ? i + 1 : 0;
animate(this, i);
});
});
function calculateBackgroundPosition(index)
{
return "0 " + (index * 50 * -1) + "px";
}
function animate (that, i)
{
var position = calculateBackgroundPosition(i);
$(that).parent().find(".hjul").animate({"backgroundPosition": position});
}
これも実際の例です。
最後の画像に到達して最初からやり直す必要があるとき、またはその逆のときは完全に動作しませんが、現時点で最高です。
アップデート3:
i
複数のホイールで機能させるには、ホイールごとに個別のカウンター変数を用意する必要があります。そうでなければ、それらは互いに影響を及ぼします。IDが代わりにhjulwrapper
クラスになるように、コードを更新しました。hjulwrapper
IDは、単一の要素に固有である必要があります。したがって、それに応じてCSSを更新してください。それとは別に、コードの一部を次のように更新する必要があります。
$(function () {
$(".hjulwrapper").each(function () {
var i = 0,
numberOfImages = 5;
$(".op", this).click(function () {
// Decrease by one, and restart when we reach the first image
i = ((i - 1) >= 0) ? i - 1 : numberOfImages - 1;
animate(this, i);
});
$(".ned", this).click(function () {
// Increase by one, and restart when we reach the last image
i = ((i + 1) < numberOfImages) ? i + 1 : 0;
animate(this, i);
});
});
});
それぞれをループしてhjulwrapper
、ホイールごとに個別のスピナーを作成していることに注意してください。
これが実用的なフィドルです:http://jsfiddle.net/yEhpF/65/