正直なところ、そのアプローチは私には少し重いようです。
すでに 5 つの画像があるので、個々のボタンの押された状態と押されていない状態を含むスプライトを作成し、CSS の「background-position」プロパティを使用してスライドしてみませんか?
CSS は次のようになります。
div.buttons {
background-image: url(images/myimage.png);
background-position: 0 0;
position:relative;
width:64px;
}
div.buttons.dog{
background-position: 0 32px;
}
div.buttons.cat{
background-position: 0 64px;
}
div.buttons div.dog{
position:absolute;
left: 0;
top: 0;
width: 32px;
height: 32px;
border: transparent 1px solid;
}
div.buttons div.cat{
position:absolute;
left: 32px;
top: 0;
width: 32px;
height: 32px;
border: transparent 1px solid;
}
HTML を次のように使用します。
<div class="buttons">
<div class="dog"></div>
<div class="cat"></div>
</div>
そして、次のようなjQueryの簡単なもの:
$('div.buttons').children().each(function(){
$(this).click(function() { $(this).parent().addClass($(this).attr('class')).removeClass($(this).siblings().attr('class'));
});
アップデート
質問者のリクエストによると、ボタンレイヤーに div オーバーレイを実装する方法は次のとおりです。まず、div.buttons
最上部の CSS ブロックから始めます。スプライトの代わりに、デフォルトの「オフ」位置のボタンに画像を使用します。
次に、このようなコンテナーを 4 つ作成します (div
ここでは s を使用しましたが、コンテナーに適切なセマンティック コンテキストを提供する任意の要素を使用できると考えられます)。
CSS
div.buttons{
background-image: url(images/myimage.png);
background-position: 0 0;
position:relative;
width:136px; /* whatever your width for the image is */
}
div.fish, div.rabbit, div.dog, div.cat {
position: absolute;
top: 0;
background-size: cover;
height: 24px; /* Whatever the height of your buttonbar is */
}
div.cat{
width: 32px; /* Width of your button */
left: 0;
background-image: none;
}
div.on.cat {
background-image: url(path/to/catImage.png);
}
div.dog {
left: 32px; /* The width of the preceding button(s), if they exist */
width: 40px; /* Width of your button */
background-image: none;
}
div.on.dog {
background-image: url(path/to/dogImage.png);
}
div.rabbit {
left: 72px; /* The width of the preceding button(s), if they exist */
width: 32px; /* Width of your button */
background-image: none;
}
div.on.rabbit {
background-image: url(path/to/rabbitImage.png);
}
div.fish {
left: 104px; /* The width of the preceding button(s), if they exist */
width: 40px; /* Width of your button */
background-image: none;
}
div.on.fish {
background-image: url(path/to/fishImage.png);
}
HTML
<div class="buttons">
<div class="cat"></div>
<div class="dog"></div>
<div class="rabbit"></div>
<div class="fish"></div>
</div>
これは、ボタンスライスを「ラップ」する div がその動物に一致するクラスを持っていることを前提としていますが、これは明らかにあなたが望むものである可能性があります。次に、クリック イベントで、押されたボタンに必要なクラスを適用するだけです。使用する jQuery は次のようになります。
jQuery
$('.buttons > div').on('click',function(){
var t = $(this);
t.siblings.removeClass('on');
t.addClass('on');
//Whatever your button is supposed to do normally here
});