如何在jQuery中使用hash #popup打开内容框

时间:2013-03-27 14:44:50

标签: jquery

这是基本的HTML标记。

<a id="open" href="#popup">click</a>
<div id="popup">content</div>

我默认隐藏<div id="popup">,点击<a id="open">打开<div id="popup">

如果用户输入了带有哈希标记#popup的网址,即example.com/#popup,我是否可以默认打开?

1 个答案:

答案 0 :(得分:3)

在CSS中使用display: none;

#popup {
    display: none;
}

然后在你的JS中使用其中任何一个:

$("#open").on('click', function(e) {
    e.preventDefault();
    $("#popup").toggle(); //When clicked, toggle visibility.
});

$(window).on('hashchange', function() {
    //You can detect a hash change like this
    //Since your href is set to #popup,
    //you can put the .toggle() in here as the hash will change when clicked.
    console.log("yolo");
});

if(window.location.hash == "#popup") {
    //If it is initialized with the hash #popup (ie. example.com#popup and Enter)
    //Use this
    console.log("yolo2");
    $("#popup").show();
}

Dat Fiddle