gpt4 book ai didi

javascript - 从 URL 获取 DIV 哈希值

转载 作者:行者123 更新时间:2023-11-28 01:48:21 27 4
gpt4 key购买 nike

这是建议的 fiddle - http://jsbin.com/EzUTizuf/1/edit (由于 url 导航更改,iframe 从 Codemirror JSBin 转到空白页面,这就是我之前没有添加 fiddle 的原因)

我有一个导航到#about 的 anchor 。当 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 FIDDLE:http://jsfiddle.net/H6DZH/

关于javascript - 从 URL 获取 DIV 哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20025111/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com