JSFiddle - React, Tailwind, and code Playground
HTML
<nav id="nav">
<ul>
<li><a href="#page2" onclick="scrollToPage2();return false">JS scrolltop solution
</a> </li>
</ul>
</nav>
<article id="page1" class="wrap">PAGE1</article>
<article id="page2" class="wrap">PAGE2
<div id="top">
<a onclick="scrollToTop();return false">
<p>JS滚动条</p>
<p>top</p>
</a>
</div>
</article>
CSS
* {
padding: 0;
margin: 0;
}
nav ul {
list-style: none;
float: left;
}
nav ul li {
display: inline-block;
margin: 0 20px;
}
#nav {
position: fixed;
width: 100%;
height: 10px;
background: #48D1CC;
color: #fff;
padding: 30px;
text-align: center;
z-index: 2;
}
a {
text-decoration: none;
display: inline-block;
color: #fff;
}
#page1 {
width: 100%;
height: 700px;
background: #3A5FCD;
color: #fff;
line-height: 700px;
font-size: 100px;
text-align: center;
}
#page2 {
width: 100%;
height: 700px;
background: #EE6A50;
color: #fff;
line-height: 700px;
font-size: 100px;
text-align: center;
}
#top {
float: right;
position: relative;
top: 550px;
font-size: 20px;
z-index: 1;
width: 100px;
height: 100px;
background: #333;
color: #fff;
line-height: 50px;
text-align: center;
margin: 10px;
}
JavaScript
var timeOut1;
function scrollToPage2() {
// 找到page2的位置
var $page2 = $("#page2");
var offset = $page2.offset();
// 如果滚动条没有到page2的位置
if (document.body.scrollTop < offset.top) {
// 就以每20ms滚动50的速度滚下去
window.scrollBy(0, 50);
timeOut1 = setTimeout('scrollToPage2()', 20);
} else
// 清除计时
clearTimeout(timeOut1);
};
var timeOut2;
function scrollToTop() {
// 如果没有滚回到首页
if (document.body.scrollTop != 0 || document.documentElement.scrollTop != 0) {
// 就以每20ms滚动50的速度滚上去
window.scrollBy(0, -50);
timeOut2 = setTimeout('scrollToTop()', 20);
} else
// 清除计时
clearTimeout(timeOut2);
};