从 URL 中获取 DIV 哈希

Grab DIV Hash From URL

本文关键字:DIV 哈希 获取 URL      更新时间:2023-09-26

这是建议的小提琴 - http://jsbin.com/EzUTizuf/1/edit(由于 url 导航更改了 Codemirror JSBin 的 iframe 进入空白页,这就是为什么我之前没有添加小提琴的原因)

我有一个锚导航到 #about。当 window.location 等于 #about 时,我想执行一个对应于该特定窗口位置的小函数。

这是我尝试执行此操作的最后一个代码。

if (window.location.href === "#about") {
    $('.about').show();
    document.title="About";
    alert("About DIV Shows Only From This URL!");
}

如果有人能提供帮助,将不胜感激。

谢谢!

这是完整的代码。

<!DOCTYPE html>
<html>
<head>
<title>Grab DIV Hash</title>
<meta charset='utf-8'>
<meta name='viewport' content='initial-scale=1.0'>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
<style type='text/css'>
body {
    position: absolute;
    top: 0px; left: 0px;
    width: 100%; height: 100%;
    padding:0; margin:0;
    background: #7abcff;
}
nav { text-align: center; }
a { outline: none; color: #000; text-decoration: none;}
a:hover { color: #555; }
a:active { color: #333; }
h1 {
    margin-top: .25em;
    font: bold 2.75em Arial, sans-serif;
    text-shadow: rgba(0,0,0,0.5) -1px 0, rgba(0,0,0,0.3) 0 -1px, rgba(255,255,255,0.5) 0 1px, rgba(0,0,0,0.3) -1px -2px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
    $('.about').hide();
    function AboutPage() {
        if (window.location.href === "#about") {
            $('.about').show();
            document.title="About";
            alert("About DIV Shows Only From This URL!");
        }
    }
    AboutPage();
});
</script>
</head>
<body>
    <nav>
        <a href="#about"><h1>About</h1></a>
    </nav>
    <div class="about">
        1) About link clicked!<br />
        2) This div should only be visible from whatever.com/#about
    </div>
</body>
</html>

在条件中使用window.location.hash而不是window.location.href来检测哈希的值。

代码还必须将事件处理程序附加到window.onhashchange,以检测哈希何时发生更改。 单击链接时,jQuery的ready事件不会触发,因为未加载新页面。

$(document).ready(function() {
    $('.about').hide();
    window.onhashchange = function(){
        if(window.location.hash === "#about"){
           $(".about").show();
           document.title="About";
        }
    };
});

JS小提琴:http://jsfiddle.net/H6DZH/