2014-01-12 53 views
0

我想通過URL導航到div時顯示div的內容。目前Div的內容顯示在屏幕上。如何在導航到Div時打開Div?

如何使用帶錨點的URL導航到主標題時顯示Div內容?

這裏的JavaScript

<script type="text/javascript" src="jquery-latest.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 

//Set default open/close settings 
$('.acc_container').hide(); //Hide/close all containers 
//$('.acc_trigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container 

//On Click 
$('.acc_trigger').click(function(){ 
if($(this).next().is(':hidden')) { //If immediate next container is closed... 
    $('.acc_trigger').removeClass('active').next().slideUp(); //Remove all .acc_trigger classes and slide up the immediate next container 
    $(this).toggleClass('active').next().slideDown(); //Add .acc_trigger class to clicked trigger and slide down the immediate next container 
} 
return false; //Prevent the browser jump to the link anchor 
}); 

}); 
</script> 

,這裏是我的html

<h2 class="acc_trigger"><a href="#">Some Title Goes Here</a></h2> 
<div class="acc_container"> 
    <div class="block"> 
    <h3>Strap Line Goes here</h3> 
     Text content goes here 
    </div> 
</div> 

<h2 class="acc_trigger"><a href="#">Another title Goes Here</a></h2> 
<div class="acc_container"> 
    <div class="block"> 
    <h3>Another Strap Line Goes here</h3> 
     Some more text content goes here 
    </div> 
</div>  

回答

0

如果您使用的是哈希(如url.com/page.html#otherStuff)然後讀取的location.hash

http://www.w3schools.com/jsref/prop_loc_hash.asp

如果您使用的是查詢(例如url.com/page.html?otherS凝灰岩)使用location.search

http://www.w3schools.com/jsref/prop_loc_search.asp

將要展現DIV下面的代碼,所以元素已創建。然後只需做一個簡單的if(hash == "#otherStuff"){ /* Do stuff */ }在「做東西」中,您只需運行open函數即可。

+0

謝謝大衛。恐怕我對這一切都很陌生。你能告訴我怎麼做? – Ruf1

+0

不,因爲我不知道你的hashtag或函數名稱。我並不是想要表達自己的意思,但是如果你不知道如何寫if語句,你需要從頭開始備份一些學習內容。 – David

0

收聽在window對象上觸發的hashchange事件。那麼你可以顯示div或做你想要的東西。

沿着這條線的東西;

<a href="#about">About</a> 
<div id="mydiv_about" style="display:none"> 
</div> 
<a href="#media">Media</a> 
<div id="mydiv_media" style="display:none"> 
</div> 

和一些JavaScript

window.addEventListener("hashchange", function(){ 
    document.getElementById("mydiv_"+document.location.hash.substr(1)).style.display="block"; 
},false); 

//編輯 更新,以反映工作示例

+0

謝謝japrescot。我不確定我在這裏做什麼。你能告訴我如何讓代碼工作。 – Ruf1

+0

用html和修改後的javacript更新 – japrescott

+0

Thanksyou。當我按照最初發布的方式集成到我的代碼中時,似乎無法使其發揮作用。我確定你的代碼很好,這是我缺乏經驗。 – Ruf1