Show/Hide/Toggle Multiple Divs By ID?

2019-04-02 15:55发布

The good folks at stackoverflow helped me part of the way with this, now i just need a little push over the finishing line.

I need to have a toggle button, that opens div on click (slide down) and then closes on click, pref with an active class too.

However, if you click another toggle button that child div opens and closes the previous one, IF it was open.

So basically none of the opening divs can ever be open at the same time, only one at a time.

I need this done by anchor id as the opening div is not related to the toggle button (its down the page a bit)

So far that doesn't work, but all the html is there.. http://jsfiddle.net/CkTRa/398/

Thank you so much if anyone can help, searched high and low and the nearest i found was this http://andylangton.co.uk/articles/javascript/jquery-show-hide-multiple-elements/ but it doesnt close an already open div when you click a new one.

4条回答
戒情不戒烟
2楼-- · 2019-04-02 15:57

As mentioned in other answers, for the next() to work, the layout has to be changed (see fiddle) After that, to close all toggle divs first, you can use:

$(".toggle").slideUp("slow");

but to prevent interfering with the div that is expanded, the not can be used to exclude that div:

var div = $(this).next(".toggle");
$(".toggle").not(div).slideUp("slow");
div.slideToggle("slow");

The combined fiddle: http://jsfiddle.net/CkTRa/402/

查看更多
ら.Afraid
3楼-- · 2019-04-02 16:16

DEMO

  $("a").click(function(){
    var myelement = $(this).attr("href")
    $(myelement).slideToggle("slow");
    $(".toggle:visible").not(myelement).hide();

  });

查看更多
劫难
4楼-- · 2019-04-02 16:18

Here's a jsFiddle that fetches the right div based on the href in your anchor tag:

Basically:

 $( $(this).find("a").attr('href') ).slideToggle("slow");

Edit:

jsFiddle that hides any open ones, not being the current

Basically:

var divToToggle = $( $(this).find("a").attr('href') );
$(".toggle:visible").not(divToToggle).hide();
divToToggle.slideToggle("slow");
查看更多
小情绪 Triste *
5楼-- · 2019-04-02 16:19
<h3 class = "trigger" href="#box1">Heading 1</h3>.

is better than:

<h3 class = "trigger"><a href="#box1">Heading 1</a></h3>.

You get display trouble with the second option when the content slides back.

查看更多
登录 后发表回答