kar*_*m79 10
为URL添加哈希就像操作一样简单location.hash,例如:
$("a.live").click(function() {
window.location.hash = 'live'; // not needed if the href is '#live'
});
Run Code Online (Sandbox Code Playgroud)
您可以轻松测试其存在并根据页面加载时的值进行相应操作,例如:
$(document).ready(function() {
var hashVal = window.location.hash.split("#")[1];
if(hashVal == 'live') {
$("#live").show();
}
});
Run Code Online (Sandbox Code Playgroud)
如果你有这样的标记:
<a href="#div5" class="toggler">Toggle Div 5</a>
<div id="div5">Content for Div 5</div>
Run Code Online (Sandbox Code Playgroud)
你可以在jQuery中做到这一点:
$("a.toggler").click(function() {
$(this.hash).slideToggle();
});
Run Code Online (Sandbox Code Playgroud)
或者使用rel或点击你点击的div,如下所示:
<div rel="#div5" class="toggler">Toggle Div 5</a>
<div id="div5">Content for Div 5</div>
Run Code Online (Sandbox Code Playgroud)
并将你的jQuery调整为:
$("div.toggler").click(function() {
var hash = $(this).attr("rel");
$(hash).slideToggle();
window.location.hash = hash;
});
Run Code Online (Sandbox Code Playgroud)
我的建议是display:block;在锚点上使用你想做的事情,并利用这里的默认浏览器行为,它会处理点击的哈希值.
无论上面采用哪种方法,您都可以在页面加载中显示如下:
$(function() {
if(location.hash != "") {
$(location.hash + ":hidden").slideDown();
}
});
Run Code Online (Sandbox Code Playgroud)