Hexo优化:添加返回顶部按钮

参考Jack的blog,成功添加了返回顶部按钮。

添加HTML代码

新建文件\themes\light\layout\_partial\totop.ejs,打开后添加如下:

1
2
3
<div id="totop" style="position:fixed;bottom:150px;right:50px;cursor: pointer;">
<a title="返回顶部"><img src="/imgs/scrollup.png"/></a>
</div>

添加JS代码

新建文件\themes\light\source\js\totop.js,打开后添加如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
(function($) { 
	// When to show the scroll link
	// higher number = scroll link appears further down the page   
	var upperLimit = 1000;
	
	// Our scroll link element
	var scrollElem = $('#totop');
   
	// Scroll to top speed
	var scrollSpeed = 500;
   
	// Show and hide the scroll to top link based on scroll position   
	scrollElem.hide();
	$(window).scroll(function () {            
		var scrollTop = $(document).scrollTop();       
		if ( scrollTop > upperLimit ) {
			$(scrollElem).stop().fadeTo(300, 1); // fade back in           
		}else{       
			$(scrollElem).stop().fadeTo(300, 0); // fade out
		}
	});

	// Scroll to top animation on click
	$(scrollElem).click(function(){
		$('html, body').animate({scrollTop:0}, scrollSpeed); return false;
	});
})(jQuery);

修改upperLimitscrollSpeed可以修改显示位置和回滚速度。

添加引用

修改\themes\light\layout\_partial\after_footer.ejs,在末尾添加:

1
2
<%- partial('totop') %>
<script src="<%- config.root %>js/totop.js"></script>

添加按钮图片

将图片放到\themes\light\source\imgs下,命名为scrollup.png


WELL DONE!