3

背景: クラス .big1、.big2、.big3、および .small1、.small2、.small3 を持つ 9 つの div があります。div は兄弟または親と子ではありません。または、純粋な CSS でこれを行うことになります。

.small1 をホバーすると .big1 にクラスを追加し、small2 をホバーすると .big2 にクラスを追加します。私の現在のアプローチ(以下に示す)は機能しますが、エレガントではありません。私は jQuery にはかなり慣れていませんが、変数を使用してそれに応じてクラス名を変更し、コードを単一の .addClass 関数に縮小することは可能だと思います。

問題:ホバーされた .big*x* div の末尾にある数字xが、それに続く .small*x* div のクラス名に追加される ようにコードをセットアップしようとしています。おそらく、変数 out を作成することによります。 .big および .small クラスの数値の。これは私が立ち往生しているところです。.split() を使用して .small の末尾にある数値を取得し、.replace() を使用してその数値を .big の末尾に配置することを検討しましたが、設定方法がわかりません. 提案は大歓迎です!

jQuery:

$('.small1').hover(
  function(){
    $('.big1').addClass("itemHover");
  },function(){
    $('.big1').removeClass("itemHover");
});

$('.small2').hover(
  function(){
    $('.big2').addClass("itemHover");
  },function(){
    $('.big2').removeClass("itemHover");
});

$('.small3').hover(
  function(){
    $('.big3').addClass("itemHover");
  },function(){
    $('.big3').removeClass("itemHover");
}); 

簡略化された HTML: (繰り返しますが、マークアップの div は兄弟または親/子ではありません)

<div class="big1"></div>
<div class="big2"></div>
<div class="big3"></div>
<div class="small1"></div>
<div class="small1"></div>
<div class="small2"></div>
<div class="small2"></div>
<div class="small3"></div>
<div class="small3"></div>

更新/解決策: これは、@Sergio の解決策のいくつかの行を明確にするためのものです。FF のコードを壊していた欠落したブラケットがいくつかありました。以下のソリューションは、IE 10、Chrome、および FF で正常にテストされました。

$('div[class^="small"]').hover(function () {
    var this_class = $(this).prop('class');
    var filter = $.grep(this_class, function (a) {
        return a ^= 'small';
    });
    $('div.big' + filter).addClass("itemHover");
}, function () {
    $('div[class^="big"]').removeClass("itemHover");
});
4

2 に答える 2

1

class nameで始まるクラスの小文字を削除して、smallクラスで番号を取得し、その番号をクラスで使用できますbig

ライブデモ

$('[class^=small]').hover(     
  function(){  
      num = this.className.replace('small', '');
    $('.big' + num).addClass("itemHover");

  },function(){
      num = this.className.replace('small', '');
    $('.big' + num).removeClass("itemHover");
}); 
于 2013-09-01T06:53:26.477 に答える