问题
Basically, what I need is to get the fancybox links to change the url in the address bar to something like this: www.website.com/page/#lightbox
Also, if I were to visit www.website.com/page/#lightbox, then the lightbox corresponding to that link will automatically open.
A great example of this is in this site: http://www.rudirakete.de/rudirakete/main#2008-10-5-1524260693
回答1:
The trick is to make a single function for displaying the content you want, based on some hashtag. The simplest way to do that is make the value of the hashtag also the ID of some element on the page you want to display in fancybox (although by no means required).
Then, just use the hashtags for your link hrefs, and do not use jQuery's preventDefault()
function on those links. That way, those links will alter the url bar, appending the hash tag that you set as their href values. Then, attach the function to display the fancybox to those links.
Finally, call that function with the value of location.hash
as your argument.
Just whipped this up as a simple example. Seems to do what you want it to.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="fb/fb.js" type="text/javascript"></script>
<link rel="stylesheet" href="fb/fb.css" type="text/css" media="screen" charset="utf-8" />
<script type="text/javascript" charset="utf-8">
$(function(){
function showfb(id) {
switch(id) {
case '#fb1':
case '#fb2':
// Gotta do this so that fb can measure the content dimensions
$(id).show();
$.fancybox({
href: id,
type:'inline',
// This is so that the content doesn't just pop back on to the
// page when finished. Of course, if you're not using inline content
// then this may not apply
onClosed: function() {
$(id).hide();
}
});
break;
}
}
showfb(location.hash);
$('a.fblink').click(function(e){
showfb($(this).attr('href'));
});
});
</script>
<style type="text/css" media="screen">
/* I'm assuming you want the fancybox content to
ONLY be displayed in the fancybox. Once again, if using
ajax or some other method of getting fancybox content, this might
not be necessary */
.fb { display: none; }
</style>
</head>
<body>
<p>
<a class='fblink' href="#fb1">Show 1</a>
</p>
<p>
<a class='fblink' href="#fb2">Show 2</a>
</p>
<div id="fb1" class="fb">This is a test</div>
<div id="fb2" class="fb">This is another test</div>
</body>
</html>
来源:https://stackoverflow.com/questions/7843823/fancybox-link-that-changes-the-url-in-address-bar-and-links-to-a-page-with-an-o