2016-09-19 13 views
1

解決できないjQueryの問題が残っています。 私はサブメニュー要素を持つメニューを作成しました。メニュー項目をクリックしてコンテンツの高さを切り替えたい。他のアイテムをクリックすると、コンテンツが崩壊します。説明するのが難しい種類の、私は仕事をしている2つのウェブサイトを入れました http://www.polerstuff.com/ - > 'ショップ'をクリックしてから '情報'をクリックすると、サブメニューが開いたままです。同じトリックがここに見られたhttp://topodesigns.com/Unfoldサブメニューの条件(jQuery)

これらの2つのウェブサイトはShopifyを使用していると思います。 >事前に多くのことを感謝 -

$(document).ready(function() { 
    $(".button").on("click", function() { 
     if($(".content").height() == 0) { 
      $(".content").animate({height: "300px"}); 
     } 
     else if($(".content").height() == 300) { 
      $(".content").animate({height: "0px"}); 
     } 
    }); 
}); 

はここjsfiddle は私です。

答えて

1

データ属性を使用してdivを目的のコンテンツにターゲティングし、目的の高さを含む別のデータタグを使用してアニメーション化するフィディドのバージョンです(他にも多数あります)。 同じボタンをクリックすると、それを閉じたままにします。これは、表示クラスを追加することで実現します。 '非表示'のdivには、必要に応じてクラスとレイアウトを含むdivを追加することができます。

$(document).ready(function(){ 
 
    $(".b").on("click", function(){ 
 
    
 
     var $this = $(this), 
 
    \t target = $this.data('target'), 
 
      tall = $this.data('tall'), 
 
      content = $(".content"); 
 
      
 
     target = $('.'+target).html(); // get the html content of target divs 
 
     content.html(target); // insert said content 
 
      
 
     \t if (!$this.hasClass('on')) { // if it hasn't been clicked yet.. 
 
      $(".b").removeClass('on'); // say that none have been clicked 
 
\t \t $this.addClass('on');  // say that just this one has been clicked 
 
      content.animate({height: tall}, 200); // animate to the height specified in this buttons data attribute 
 
     } else { 
 
      content.animate({height: "0px"}); 
 
\t \t $this.removeClass('on'); 
 
     } 
 
    }); 
 
});
.content { 
 
    background: coral; 
 
    width: 100%; 
 
    height: 0px; 
 
    overflow:hidden; 
 
} 
 

 
.hiding{ 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 

 
<button class="b" data-target="alpha" data-tall="4em">Button</button> 
 
<button class="b" data-target="bravo" data-tall="7em">Button</button> 
 
<button class="b" data-target="charlie" data-tall="5em">Button</button> 
 

 
<div class="content">Le contenu</div> 
 

 
<div class="hiding alpha"> some stuff </div> 
 
<div class="hiding bravo"> other things </div> 
 
<div class="hiding charlie"> bits and pieces </div>

+0

素晴らしい、それは魔法のように動作します。私は良い考えではなかったトグルの側を見ていました。私はちょうどhtmlコンテンツにフェード効果を追加する必要がありますが、あなたは私の一日を作った。ありがとうございました –

+0

問題はありません@BrunoLandowskiコンテンツのdivに再配置された高さのデータがここにあります(より良いHTML構造化のために)、フェードインします:https://jsfiddle.net/wrx0uf3m/ – Sam0