为页面转换创建链接
问题描述:
我在写单页网站。它有3个“幻灯片”,如About/Music/Contact。通过下拉菜单可以访问这些幻灯片。当您单击菜单中的链接时,当前的页面包装将变为visibility: hidden
,并通过动画显示以下内容。这很有效,但所有事情都发生在根页面上,而不更改URL,这不便于用户使用,因为如果要共享指向页面的链接,您将始终将其重定向到根目录。为页面转换创建链接
所以问题是:“如何在不点击重新加载页面的情况下更改URL(可能是通过散列或者不适用)?”。提前致谢。
P.S.没有代码需要,只需给我你的方式来做到这一点,我将它添加到代码中。
答
这个只是检查,并采取它,如果你想要这个
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
// click-to-scroll behavior
$("a").click(function (e) {
e.preventDefault();
var section = this.href;
var sectionClean = section.substring(section.indexOf("#"));
$("html, body").animate({
scrollTop: $(sectionClean).offset().top
}, 1000, function() {
window.location.hash = sectionClean;
});
});
// listen for the scroll event
$(document).on("scroll", function() {
//console.log("onscroll event fired...");
// check if the anchor elements are visible
$(".common").each(function (idx, el) {
if (isElementInViewport(el)) {
// update the URL hash
if (window.history.pushState) {
var urlHash = "#" + $(el).attr("id");
window.history.pushState(null, null, urlHash);
}
}
});
});
body {
float: left;
width: 100%;
padding-bottom: 0px;
}
.common {
\t width: 100%;
\t float: left;
\t height: 100vh;
\t display: table;
}
.allbody {
\t float: left;
\t width: 100%;
}
a {
\t display: inline-block;
\t padding: 15px;
}
header {
\t float: left;
\t width: 100%;
\t position: fixed;
\t top: 0;
\t left: 0;
\t background: #fff;
}
.common h2 {
\t font-size: 30px;
\t color: #fff;
\t text-align: center;
\t padding-top: 10%;
\t display: table-cell;
\t vertical-align: middle;
}
#firstDestination {
\t background: #000;
}
#secondDestination {
\t background: #999;
}
#thirdDestination {
\t background: #ccc;
}
#fourthDestination {
\t background: #c1c1c1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<header>
\t <a href="#firstDestination">first page</a>
\t <a href="#secondDestination" >second page</a>
\t <a href="#thirdDestination">third page</a>
\t <a href="#fourthDestination">fourth page</a>
</header>
<div class="allbody">
\t <div class="common" id="firstDestination" ><h2>First Page</h2></div>
\t <div class="common" id="secondDestination"><h2>Second Page</h2></div>
\t <div class="common" id="thirdDestination" ><h2>Third Page</h2></div>
\t <div class="common" id="fourthDestination" ><h2>Fourth Page</h2></div>
</div>
我可以显示一个简单的演示代码? –