<分区>
标签 javascript jquery html css
<分区>
我正在设计一个网站,在同一个索引文件中有 4 个页面,其中一次只有一个页面处于事件状态。我的主页上有 3 个链接。当我单击主页链接时,我需要滚动到另一个页面中的特定 div。我试图实现这一点,但它并没有滚动到特定的 div,而是只显示了该部分。
最佳答案
我想你正在寻找这样的东西,全屏运行代码片段,然后检查这是否是你需要的
body {
float: left;
width: 100%;
padding-bottom: 0px;
}
.common {
width: 100%;
float: left;
height: 100vh;
display: table;
}
.allbody {
float: left;
width: 100%;
}
a {
display: inline-block;
padding: 15px;
}
header {
float: left;
width: 100%;
position: fixed;
top: 0;
left: 0;
background: #fff;
}
.common h2 {
font-size: 30px;
color: #fff;
text-align: center;
padding-top: 10%;
display: table-cell;
vertical-align: middle;
}
#firstDestination {
background: #000;
}
#secondDestination {
background: #999;
}
#thirdDestination {
background: #ccc;
}
#fourthDestination {
background: #c1c1c1;
}
<body>
<header>
<a href="#firstDestination">first page</a>
<a href="#secondDestination" >second page</a>
<a href="#thirdDestination">third page</a>
<a href="#fourthDestination">fourth page</a>
</header>
<div class="allbody">
<div class="common" id="firstDestination" ><h2>First Page</h2></div>
<div class="common" id="secondDestination"><h2>Second Page</h2></div>
<div class="common" id="thirdDestination" ><h2>Third Page</h2></div>
<div class="common" id="fourthDestination" ><h2>Fourth Page</h2></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
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);
}
}
});
});
</script>
关于javascript - 单击链接时滚动到另一个部分的特定 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41481286/