Jquery Accordion – 用href链接打开

我在stackoverflow的帮助下创建了一个脚本。

目前我的代码看起来像

 $(function() { $( "#accordion" ).accordion(); var hashId = 0, $accordion = $('#accordion'); if (window.location.hash) { $accordion.children('h3').each(function(i){ var txt = $(this).text().toLowerCase().replace(/\s+/g,'_'); this.id = txt; if (txt === window.location.hash.slice(1)) { hashId = i; } }); } $accordion.accordion({ active: hashId, animate: true, heightStyle: 'content', collapsible: true, create: function( event, ui ) { $accordion.children('h3').each(function(i){ $(this).before(''); }); $accordion.find('.accordion-link').click(function(){ $accordion.accordion( "option", "active", $(this).data('index') ); }); } }); });  

我唯一的问题是,我怎么能默认关闭第一个手风琴?

HTML:

 

Link1

content

Link2

content

谢谢,克里斯

UPDATE

我现在删除了第三行 – 代码如下:

  $(function() { var hashId = 0, $accordion = $('#accordion'); if (window.location.hash) { $accordion.children('h3').each(function(i){ var txt = $(this).text().toLowerCase().replace(/\s+/g,'_'); this.id = txt; if (txt === window.location.hash.slice(1)) { hashId = i; } }); } $accordion.accordion({ active: hashId, animate: true, heightStyle: 'content', collapsible: true, create: function( event, ui ) { $accordion.children('h3').each(function(i){ $(this).before(''); }); $accordion.find('.accordion-link').click(function(){ $accordion.accordion( "option", "active", $(this).data('index') ); }); } }); });  

你需要做的是用…初始化你的手风琴

 $("#accordion").accordion({ active: false, collapsible: true }); 

…然后移动你的“主动哈希手风琴”代码

 if (windows.location.hash) 

最终看起来像这样:

 $(function () { var hashId = 0, $accordion = $("#accordion") .accordion({ active: false, collapsible: true }); if (window.location.hash) { $accordion.children('h3').each(function (i) { var txt = $(this).text().toLowerCase().replace(/\s+/g,'_'); this.id = txt; if (txt === window.location.hash.slice(1)) hashId = i; }); $accordion.accordion ({ active: hashId, animate: true, heightStyle: 'content', collapsible: true, create: function ( event, ui ) { $accordion.children('h3').each(function (i) { $(this).before(''); }); $accordion.find('.accordion-link').click(function () { $accordion.accordion( "option", "active", $(this).data('index') ); }); } }); } }); 

全部崩溃: http //codepen.io/anon/pen/kLbeD

链接1活动: http //codepen.io/anon/pen/kLbeD#link1

链接2活跃: http //codepen.io/anon/pen/kLbeD#link2

看看手风琴的可折叠属性 。 它被定义为:

是否可以立即关闭所有部分。 允许折叠活动部分。

使用它的代码是:

 $('#accordion').accordion({ collapsible: true }); 

使用属性active:false有效

演示: http : //jsfiddle.net/robschmuecker/Tajhr/

http://api.jqueryui.com/accordion/#option-active

 $accordion.accordion({ active: false, animate: true, heightStyle: 'content', collapsible: true, create: function (event, ui) { $accordion.children('h3').each(function (i) { $(this).before(''); }); $accordion.find('.accordion-link').click(function () { $accordion.accordion("option", "active", $(this).data('index')); }); } });