下面是建议使用的http://jsbin.com/EzUTizuf/1/edit (因为url导航更改了Codemirror JSBin的iframe到一个空白页,这就是为什么我以前没有添加小提琴)
我有一个锚导航到#约。当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>
发布于 2013-11-16 15:14:19
在条件中使用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";
}
};
});
https://stackoverflow.com/questions/20025111
复制