原创 

html 原生js 返回到顶部源代码Demo

分类:前端,js    728人阅读    IT小君  2021-12-04 21:45

html(关键是id,样式请自己定义):

<div
	  class="ivu-back-top ivu-back-top-show" id="gotop"
	  style="bottom: 50px; right: 30px;display:none"
	>
	  <div class="ivu-back-top-inner">
		<i class="ivu-icon ivu-icon-ios-arrow-up"></i>
	  </div>
	</div>
</div>

js:

<script>
 var oA = null
    window.onload = function() {
        oA = document.getElementById('gotop');
 
        oA.onclick = function() {
            toScroll("top")
        }
		 setInterval(function() {
            var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
			if(scrolltop>20){
				oA.style.display='block'
			}else{
				oA.style.display='none'
			}
        }, 30)
    }
	
    function toScroll(target) {
        clearInterval(this.timer)
        var scrollHeight = document.body.offsetHeight - document.documentElement.clientHeight;
        this.timer = setInterval(function() {
            var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
            switch (target) {
                case 'top':
                    window.scrollBy(0, -100);
                    if (Math.ceil(scrolltop) <= 0) {
                        clearInterval(this.timer)
						oA.style.display='none'
                    };
                    break;
                case 'bottom':
                    window.scrollBy(0, 100);
                    if (Math.ceil(scrolltop) >= scrollHeight) {
                        clearInterval(this.timer)
                    };
                    break;
            }
        }, 30)
    }
 </script>


支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»