JSFiddle - React, Tailwind, and code Playground
HTML
<nav id="nav">
<ul>
<li><a href="#page2" onclick="scrollToPage2();return false">JS scrolltop solution
</a> </li>
<li><a href="#page3" onclick="haha();">JS animate solution</li>
<li><a href="#haha"> CSS3 solution #page1</a> </li>
<li><a href="#haha2"> CSS3 solution #page2</a> </li>
</ul>
</nav>
<a id="haha"></a>
<a id="haha2"></a>
<article id="page1" class="wrap">PAGE1</article>
<article id="page2" class="wrap"><span>PAGE2</span>
<div id="top">
<a onclick="scrollToTop();return false">
<p>JS滚动条</p>
<p>top</p>
</a>
</div>
<div id="top">
<a onclick="scrollToTop_method2();return false">
<p>JS animate</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;
transition: transform .5s ease-in-out;
}
#page2 {
width: 100%;
height: 700px;
background: #EE6A50;
color: #fff;
line-height: 700px;
font-size: 100px;
text-align: center;
transition: transform .5s ease-in-out;
}
#page2 span{
position: relative;
top: 0;
}
#haha:target ~ .wrap {
transform: translateY(0px);
}
#haha2:target ~ .wrap {
transform: translateY( -700px);
}
#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() {
var $page2 = $("#page2");
var offset = $page2.offset();
if (document.body.scrollTop < offset.top) {
window.scrollBy(0, 50);
timeOut1 = setTimeout('scrollToPage2()', 20);
} else {
clearTimeout(timeOut1);
}
}
var timeOut2;
function scrollToTop() {
if (document.body.scrollTop != 0 || document.documentElement.scrollTop != 0) {
window.scrollBy(0, -50);
timeOut2 = setTimeout('scrollToTop()', 30);
} else clearTimeout(timeOut2);
}
function haha() {
var $page2 = $("#page2");
var offset = $page2.offset();
console.log(offset.top);
$('html,body').animate({scrollTop: offset.top}, 1000);
};
function scrollToTop_method2(){
$('html,body').animate({scrollTop: 0}, 1000);
}