原生JS完成页面下拉出现回到顶部操作

需求:

滚动区域div的scrollHeight大于window或者可视区域的height,为了提高用户体验,在页面下拉至指定高度(such:200px)出现回到顶部操作按钮。

话不多说,直接上代码

主HTML结构:

<div class="content">
	<div class="container"></div>
</div>

JS:

let contentScroll = document.querySelector('.content');
	contentScroll.addEventListener('scroll',function(){
		let st = this.scrollTop;
		let divBoolean = document.querySelector('.back-top');
		if(st>200){
			let div = document.createElement('div');
				div.classList = 'back-top';
				div.title = '回到顶部↑';
			let style = document.createElement('style');
				style.type = 'text/css';
				style.title = 'backTopCss';
				style.innerHtml = inlineCss;
			if(divBoolean){
				return;
			}else{
				this.appendChild(div);
				this.appendChild(style);
			}
			document.querySelector('.back-top').addEventListener('click',()=>{
				contentScroll.scrollTop({
					top: 0,
					behavior: 'smooth'
				})
			})
		}else{
			if(divBoolean){
				this.removeChild(divBoolean);
				this.querySelector('style[title="backTopCss"]').remove();
			}
		}
	})
//inlineCss
var inlinecss = '.back-top{width: 45px; height: 45px; position: absolute; right: 50px; bottom: 50px; border-radius: 50%;box-shadow: 0 0 10px #ccc; background: #fff; cursor: pointer}.back-top:before{content: ""; width: 0; height: 0; border-right: 10px solid transparent; border-left: 10px solid transparent; border-bottom: 10px solid #5ec2a6; display: block;  position: absolute; left: 13px; top: 16px; border-radius: 2px}.back-top:hover{box-shadow: 0 0 10px #5ec2a6}'	

以上即是原生JS完成回到顶部全部功能
效果图:
在这里插入图片描述

发布了23 篇原创文章 · 获赞 10 · 访问量 400

猜你喜欢

转载自blog.csdn.net/qq_35593965/article/details/103677067
今日推荐