需求:
滚动区域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完成回到顶部全部功能
效果图: