2015-11-19 147 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