Home » Code » 返回顶部-javascript的简单实现

返回顶部-javascript的简单实现

最近很少上文章了,来水一个凑数。做一个很简单又常见的小功能吧——返回顶部。

最最简单的实现是加一个锚点——一个a链接href=”#”即可,但这样子用户体验不是很好,一是速度太快,嗖的就回到顶部了,二是中间不能停。因此一般都是用javascript实现。下面上自己的代码:

;(function(window, document){
	var BackToTop = function(selector, options){
		var elems = document.querySelectorAll(selector);
		var timer;
		for (var i = 0, len = elems.length; i < len; i++){
			elems[i].style.display = "none";
			elems[i].onclick = animateToTop;
		}

		window.onscroll = function(){
			var distance = document.documentElement.scrollTop || document.body.scrollTop;
			if (distance > window.innerHeight){
				for (var i = 0, len = elems.length; i < len; i++){
					elems[i].style.display = "inline-block";
				}
			}else{
				for (var i = 0, len = elems.length; i < len; i++){
					elems[i].style.display = "none";
				}
			}
		}

		if (options.scrollStop){
			if (typeof window.onmousewheel  === "undefined"){
				window.addEventListener("DOMMouseScroll", function(){
					clearInterval(timer);
				})
			}else{
				window.onmousewheel = function(){
					clearInterval(timer);
				}
			}

		}

		if (options.mousedownStop){
			window.onmousedown = function(){
				clearInterval(timer);
			}
		}

		function animateToTop(){
			timer = setInterval(function(){
				var distance = document.documentElement.scrollTop || document.body.scrollTop;
				var d = distance/13;
				if (distance > 0){
					document.documentElement.scrollTop = distance - d;
					document.body.scrollTop = distance - d;
				}else{
					clearInterval(timer);
				}
			}, 13);
		}
	}

	window.BackToTop = BackToTop;
})(window, document);

其中要处理一下滚轮事件,这个Chrome和IE是mousewheel,Firefox却是DOMMouseScroll,而且只能用addEventListener,on是没有效果的。运动动画是常用的所谓“缓冲”效果,其他复杂的效果就算了,这么一个小东西还搞那么一套。使用很简单:

new BackToTop("#back-to-top", {
	mousedownStop: true,
	scrollStop: true,
});

其中,mousedownStop:运动过程中按下鼠标是否停止,scrollStop:运动过程中滚动滚轮是停止。

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Time limit is exhausted. Please reload CAPTCHA.