2017-01-11 46 views
1

嗨,我有簡單的單頁網站#節。我正在使用#來隱藏和顯示部分。#url部分隱藏並顯示

例如; someurl/index.html/#sectionOne 有「sectionOne」id的div,所以我可以顯示相關部分。

我的問題是有沒有辦法預防或URL與像更換「/」字符路徑;

someurl/index.html中/ sectionOne - > someurl/index.html中/ #sectionOne

,因爲它給當然404。 我試過在卸載之前,窗口在加載,身體在加載,但這些都沒有解決我的問題。

這是簡單的例子

$(document).ready(function() { 
 
    window.onload = function(event) { 
 
     var hash = "about"; 
 
     $("section").hide(); 
 
     $("#" + hash).show(); 
 
    }; 
 

 
    $(".nav").click(function() { 
 
     console.log("CLICK"); 
 
     var hash = $(this).attr('href').substring(1); 
 
     console.log(hash); 
 
     $("section").hide(); 
 
     $("#" + hash).show(); 
 
    }); 
 
});
section {display: none;}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
 

 
<ul> 
 
    <li><a class="nav" href="#about">ABOUT</a></li> 
 
    <li><a class="nav" href="#services">SERVICES</a></li> 
 
    <li><a class="nav" href="#contact">CONTACT</a></li> 
 
</ul> 
 

 
<section id="about"> 
 
    <h1>ABOUT</h1> 
 
    <p>About section</p> 
 
</section> 
 

 
<section id="services"> 
 
    <h1>SERVICES</h1> 
 
    <p>Services section</p> 
 
</section> 
 

 
<section id="contact"> 
 
    <h1>CONTACT</h1> 
 
    <p>Contact section</p> 
 
</section>

回答

2

如果我理解正確,target僞類可以用在這裏:

section { 
 
    display: none; 
 
} 
 
#about:target, 
 
#services:target, 
 
#contact:target { 
 
    display: block; 
 
}
<ul> 
 
    <li><a class="nav" href="#about">ABOUT</a> 
 
    </li> 
 
    <li><a class="nav" href="#services">SERVICES</a> 
 
    </li> 
 
    <li><a class="nav" href="#contact">CONTACT</a> 
 
    </li> 
 
</ul> 
 

 
<section id="about"> 
 
    <h1>ABOUT</h1> 
 
    <p>About section</p> 
 
</section> 
 

 
<section id="services"> 
 
    <h1>SERVICES</h1> 
 
    <p>Services section</p> 
 
</section> 
 

 
<section id="contact"> 
 
    <h1>CONTACT</h1> 
 
    <p>Contact section</p> 
 
</section>


關於防止用戶使用/(讓它成爲任何東西)來導航,我相信從客戶端單獨完成沒有簡單的方法。

我們可以使用window.onbeforeunload事件,並讓對話框被顯示,以根據用戶是否想要保留用戶。

我看到的另一個選擇是使用React Router for client-side 404

+0

非常感謝,但我並不完全是這個意思。我想阻止用戶輸入「/」路徑字符,或者如果存在「/」路徑字符而不是「#」哈希,請用#替換它。 someurl/index.html/about - > someurl/index.html#關於 –

+0

明白了您的觀點。關於防止用戶使用'/'導航(讓它成爲任何東西),我認爲從客戶端單獨完成並不容易。幾乎沒有任何建議更新了答案。 –