2015-11-19 150 views
0

我想访问我的网站:http://testsite.com/#accordion2,并为它定下&开放第二个手风琴。我如何实现这一目标?如果网址为#accordion1,我也希望这可以发生在第一个手风琴上。打开特定的手风琴菜单

这里是我的小提琴:http://jsfiddle.net/jmjmotb3/

function close_accordion_section(source) { 
 
     $(source).parent().find('.accordion-section-title').removeClass('active'); 
 
     $(source).parent().find('.accordion-section-content').slideUp(300).removeClass('open'); 
 
    } 
 

 
    $('.accordion-section-title').click(function(e) {  
 
     if($(e.target).is('.active')) { 
 
      close_accordion_section(e.target); 
 
     }else { 
 
      $(this).addClass('active'); 
 
      $(e.target).parent().find('.accordion-section-content').slideDown(300).addClass('open') 
 
     } 
 

 
     e.preventDefault(); 
 
    });
.accordion { 
 
    overflow: hidden; 
 
    margin-bottom: 40px; 
 
} 
 

 
.accordion-section { 
 
    padding: 15px; 
 
    border: 1px solid #d8d8d8; 
 
    background: #fbfbfb; 
 
} 
 

 
.accordion-section-title { 
 
    width: 100%; 
 
    display: inline-block; 
 
    background: url("http://placehold.it/50x50") top right no-repeat; 
 
} 
 

 
.accordion-section-title.active, .accordion-section-title:hover { 
 
    text-decoration: none; 
 
} 
 

 
.accordion-section-content { 
 
    padding: 15px 0; 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div id="accordion1" class="accordion"> 
 
    <div class="accordion-section"> 
 
     <a class="accordion-section-title" href="#accordion-1">More information</a> 
 
    <div id="accordion-1" class="accordion-section-content"> 
 
     <p>Text.</p> 
 
     <p> 
 
    </div> 
 
    </div> 
 
</div> 
 
    
 
    <div id="accordion2" class="accordion"> 
 
    <div class="accordion-section"> 
 
     <a class="accordion-section-title" href="#accordion-1">More information 2</a> 
 
    <div id="accordion-1" class="accordion-section-content"> 
 
     <p>Text.</p> 
 
     <p> 
 
    </div> 
 
    </div> 
 
</div>

回答

1

检查window.location.hash财产,并从那里走。

document.addEventListener('DOMContentLoaded', function() { 

    if (window.location.hash === 'x') { 
     // do x 
    } 

}); 
+0

谢谢你,Brian。那么我如何将这个融入到我目前的解决方案中呢? – michaelmcgurk

+1

嘿迈克尔。那么你现在的解决方案需要一些调整,就像你有一个close_accordion_section函数一样,你也应该有一个open_accordion_section函数。一旦你有了,那么在准备好之后,你需要调用'open_accordion_section(window.location.hash)'。我在这里设置了一个简单的例子,但是在抓取位置哈希值方面,小提琴似乎有点挑剔,所以我只是将它硬编码在dom预处理程序的顶部。 http://jsfiddle.net/agentfitz/su5xxzav/6/ –

+0

绝对太棒了,Brian!是的,当我尝试将哈希引入时,我也得到了小提琴的小故障。我将它添加到我当前的代码名称并报告回来。谢谢!!! – michaelmcgurk