开发者

jQuery Toggle Div Switcher

开发者 https://www.devze.com 2023-01-09 18:53 出处:网络
I\'m trying to build an FAQ page. The page will have 2 columns: first column will have list of questions, second column will have the answers.

I'm trying to build an FAQ page. The page will have 2 columns: first column will have list of questions, second column will have the answers.

Essentially I'd like to hide the answer column and when a question is clicked, it will fade in. When another question is clicked, the old answer will fade out and the new answer fades in. So I guess a toggle/switch effect?

Here is the structure of my html output from Drupal:

<!-- Question column -->

<div id="question>

     <div class="views-row views-row-1">
          <div class="question">Question 1 Here!</div>
     </div>

     <div class="views-row views-row-2">
          <div class="question>Question 2 Here!</div>
     </div>

      <div class="views-row views-row-3">
          <div class="question>Question 3 Here!</div>
     </div>

</div>


<!-- Answer column -->

<div id="answer>

     <div class="views-row views-row-1">
          <div class="answer">Answer 1 Here!</div>
     </div>

     <div class="views-row views-row-2">
          <div class="answer>Answer 2 Here!</div>
     </div>

      <div class="views-row views-row-3">
          <div class="answer>Answer 3 Here!</div>
     </div>

</div>

Now here's what I managed to do so far. I've managed to make the first question toggle on/off itself with an animated fade effect. When it comes to hiding other divs to show a new div, I'm lost. Could you help tweak my jQuery plugin?

      jQuery.fn.fadeToggle = function(speed, easing, callback) {

      return this.animate({opacity: 'toggle'}, speed, easing, callback);  

      };



$(document).ready(function() {

  $("#answer .views-row").hide();

  $("#question .views-row-1").click(function(){

  $("#answe开发者_如何学JAVAr .views-row-1").fadeToggle("slow");

  });

  });

Very much appreciated for any help! Cheers.


I think this is what you're after:

jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle'}, speed, easing, callback);  
};
$(function() {
    $("#answer .views-row").hide();
    $("#question .views-row").click(function(){
        var i = $(this).index();
        $("#answer .views-row").eq(i).fadeToggle("slow").siblings().fadeOut();
    });
});

You can give it a try here, what we're doing here is getting the .index() of the <div> you clicked up top and showing the corresponding <div> at that index below (using .eq()). The .siblings().fadeOut() is just a guess, that hides the previous answer so only one at a time shows, if you want to show any number at once, just remove that portion. ​

0

精彩评论

暂无评论...
验证码 换一张
取 消