我是一个初学者,已经彻底搜索了,没有找到这个问题的解决方案。
我写了一段代码,当你点击链接时,css样式会发生变化,比如下面的代码:
function spHome(){
document.getElementById("btnHome2").style.background = "url(../images/btn_navHoverArrow.png) no-repeat center bottom";
document.getElementById("btnAccount").style.background = "0";
}
function spAccount(){
document.getElementById("btnHome2").style.background = "0";
document.getElementById("btnAccount").style.background = "url(../images/btn_navHoverArrow.png) no-repeat center bottom";
}
这个代码运行得非常好。对我来说,问题是当我刷新页面时,单击状态不再处于活动状态。是否有一个代码可以允许该功能仅在用户位于页面的某个锚点时保持活动状态。例如,如果我们有一个名为index.html#home的锚点位置,则主页按钮将处于活动状态,并且当单击index.html#account时,即使在页面刷新后,帐户按钮也将保持单击状态。
下面的例子似乎在jsfiddle上不起作用,但在所有浏览器上都可以:http://jsfiddle.net/JoshuaWaheed/HZLVt/3/
有办法做到这一点吗?
添加href散列并返回false onclick以避免页面重新加载
<a href="#home" onclick="spHome();return false" id="btnHome2" title="Home"></a>
您需要在页面加载时执行js,检查url的哈希,并将按钮的状态与哈希相对应。
使用jQuery,它将类似于(未测试):
$(function() {
if (document.location.hash == "#home")
spHome()
else
if (document.location.hash == "#account")
spAccount()
})
如果您不想使用jQuery,您可以将该代码放在docent事件"加载"