In the previous article, click the button to return to the top part of the new function
-
The button no longer appears at the bottom of the page. The button is fixed to the left or right at a distance from the bottom of the page.
.ClickTop{ display: none; color:white; padding: 5px 8px; border-radius: 10px; background: purple; position:fixed; left: 20px; bottom: 50px; z-index:3; cursor: pointer; }
2. When the visible area is on the first screen, there is no button. When the page is scrolled up a certain distance , The button appears.-
Add an event after the page starts to scroll
window.onscroll = scroll; function scroll(){ }
-
Scroll distance> 1/2 of the visible area of the window
var ScrollLength = $(document).scrollTop(); //获取滚动距离
var ViewHeight = $(window).height(); //获取可视区域的高度
-
3. Put together the final js
var Btn = $('.ClickTop');
Btn.click(function(){
$('html,body').animate({
scrollTop: 0 }, 500);
})
window.onscroll = scroll;
function scroll(){
var ScrollLength = $(document).scrollTop();
var ViewHeight = $(window).height();
//这样获取的是窗口可视区域的大小,如果改成body获取的是body的高度
console.log('页面开始滚动');
console.log(ViewHeight);
console.log(ScrollLength);
// 判断滚动距离 超过0.5倍可视区域的高度
if (ScrollLength > ViewHeight/2) {
Btn.show();
} else {
Btn.hide();
}
}
https://codepen.io/littlelittlepig/pen/xBgoYN For more code, please move to the
concise version of the demo and click to return to the top effect. Welcome to comment and correct