jQueryでボタンにかざしたらimgが変更するというものを作りたいです。
2枚の画像をクラスの中に入れてpositionで二枚の画像を2重にしてopacityでホバーしたら1枚目の画像が、外したら2枚目の画像が表示するという感じです。うまく反映されないのがなぞっちい。
jQueryのコードは多分あってると思うんですけど、動かないからあってないんでしょう。
どこが間違ってるかわからんぜよ
<div id="buttons2"> <div class="circle-b"> <button class="circle-box-b"> <span> <img src="https://www.shiftbrain.com/book/jquery/sample/chapter04/03/img/01_gr.png" alt=""> <img src="https://www.shiftbrain.com/book/jquery/sample/chapter04/03/img/01_bl.png" alt=""><br>ELEPHANT </span> </button> <button class="circle-box-b"> <span> <img src="https://www.shiftbrain.com/book/jquery/sample/chapter04/03/img/02_gr.png" alt=""> <img src="https://www.shiftbrain.com/book/jquery/sample/chapter04/03/img/02_bl.png" alt=""><br>GIRAFFE </span> </button> <button class="circle-box-b"> <span> <img src="https://www.shiftbrain.com/book/jquery/sample/chapter04/03/img/03_gr.png" alt=""> <img src="https://www.shiftbrain.com/book/jquery/sample/chapter04/03/img/03_bl.png" alt=""><br>WOLF </span> </button> <button class="circle-box-b"> <span> <img src="https://www.shiftbrain.com/book/jquery/sample/chapter04/03/img/04_gr.png" alt=""> <img src="https://www.shiftbrain.com/book/jquery/sample/chapter04/03/img/04_bl.png" alt=""><br>RHINOCEROS </span> </button> </div> </div>
一部のcssコード
.circle-b{ margin-top: 30px; position: relative; margin: 0 auto; } .circle-box-b img:first-child{ position: absolute; } .circle-box-b img:nth-child(2){ opacity:0 ; position: absolute; }
jQueryのコード
var duration = 300; $(".circle-box-b").each(function(index){ $(this).eq(index); $(".circle-box-b").eq(index).css({ top:30*index, left:220*index }); $('circle-box-b').on({ 'mouseover':function(){ var $btn = $(this).stop(true).animate({ backgroundColor:'yellow', color:'#000' },duration); $btn.find('img:first-child').stop(true).animate({ opacity:0 },duration); $btn.find('img:nth-child(2)').stop(true).animate({ opacity:1 },duration); }, 'mouseout':function(){ var $btn = $(this).stop(true).animate({ backgroundColor:'#fff', color:'#01c169' },duration); $btn.find('img:first-child').stop(true).animate({ opacity:1 },duration); $btn.find('img:nth-child(2)').stop(true).animate({ opacity:0 },duration); } }); }); });
(質問文は編集できます)質問文のコードはそれぞれコードブロックで囲んでいただけませんか? ```(バッククオート3つ)で囲み、前後に改行をいれるか、コードを選択して「<code>」ボタンを押すとコードブロックになります。