2017-01-11 42 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

明白了您的观点。关于防止用户使用'/'导航(让它成为任何东西),我认为从客户端单独完成并不容易。几乎没有任何建议更新了答案。 –