我是初学者,已经彻底搜索过,找不到解决这个问题的办法。
我写了一段代码,当你点击一个链接时,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";
}
这段代码工作得很好。我的问题是,当我刷新页面时,点击状态不再有效。是否有代码可以让该功能仅在用户位于页面的某个 anchor 时保持事件状态。例如,如果我们有一个名为 index.html#home 的 anchor 位置,则主页按钮将处于事件状态,当点击 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,您可以将该代码放在文档事件“加载”上
关于javascript - 使用 anchor 位置的 if 语句激活样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17552154/