从 URL 中获取 DIV 哈希
Grab DIV Hash From URL
这是建议的小提琴 - 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/
相关文章:
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- Steam Web API:I'我不知道该如何处理这个看起来像哈希的url来生成图像
- AngularJS:获取链接中没有哈希的查询字符串值
- 如何在Google chrome安全首选项文件中创建扩展安全哈希代码
- 如何在浏览器重新加载时保存位置哈希状态
- jQuery scrollTop-哈希错误
- 动态添加哈希标记;t工作
- 在Javascript中实现对哈希值的暴力攻击
- 如何在JavaScript/Node中计算SHA256哈希和Base64字符串编码
- 使用Javascript/jQuery以编程方式将当前锚点/哈希/片段附加到任何表单操作url
- 可以在React Native中制作一个自哈希应用程序
- 重定向不带哈希的URL-Ember.JS
- 正在测试主干事件哈希
- JavaScript对象作为哈希?复杂性是否大于O(1)
- 如何在JavaScript中实现哈希表
- 如何根据传入的哈希标签发送PHP请求
- 在我的图库(jQuery)中使用箭头导航时,更改URL中的哈希
- 从 URL 中获取 DIV 哈希
- 跨页面记住 DIV 状态.使用 cookie 或哈希
- Div 叠加层淡入历史记录,并可使用哈希 URL 添加书签