Native js realizes single page and full screen scrolling similar to fullpage
- 2021-07-13 04:08:54
- OfStack
Preface
Single-page/full-screen scrolling pages are becoming more and more common, and they are mostly used for simple pages with less content such as product introduction and recruitment. There are also many jQuery plug-ins for this effect. The effect realized in this paper is similar to the single-screen scrolling of fullpage, which is realized by native JS and does not depend on any js library.
css code:
html,body {height:100%;}
body {margin:0px;}
div {height:100%;}
html code:
<div style="background:#FEE;"></div>
<div style="background:#EFE;"></div>
<div style="background:#EEF;"></div>
<div style="background:red;"></div>
js code:
document.addEventListener("DOMContentLoaded", function() {
var body = document.body,
html = document.documentElement;
var itv, height = document.body.offsetHeight;
var page = scrollTop() / height | 0;
// Window size change event
addEventListener("resize", onresize, false);
onresize();
// Roller event
document.body.addEventListener(
"onwheel" in document ? "wheel" : "mousewheel",
function(e) {
clearTimeout(itv);
itv = setTimeout(function() {
var delta = e.wheelDelta / 120 || -e.deltaY / 3;
page -= delta;
var max = (document.body.scrollHeight / height | 0) - 1;
if (page < 0) return page = 0;
if (page > max) return page = max;
move();
}, 100);
e.preventDefault();
}
);
// Smooth scroll
function move() {
var value = height * page;
var diff = scrollTop() - value;
(function callee() {
diff = diff / 1.2 | 0;
scrollTop(value + diff);
if (diff) itv = setTimeout(callee, 16);
})();
};
//resize Events
function onresize() {
height = body.offsetHeight;
move();
};
// Gets or sets the scrollTop
function scrollTop(v) {
if (v == null) return Math.max(body.scrollTop, html.scrollTop);
else body.scrollTop = html.scrollTop = v;
};
});
For an online demonstration, please click here
Summarize
The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.