Show/Hide/Toggle Multiple Divs By ID?

£可爱£侵袭症+ 提交于 2019-12-21 06:05:33

问题


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.


回答1:


DEMO

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

  });




回答2:


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/




回答3:


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");



回答4:


<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.



来源:https://stackoverflow.com/questions/11223873/show-hide-toggle-multiple-divs-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!