市面上大部分WordPress主题都自带返回顶部按钮,也有些并没有这个功能,你需要安装相应的插件来实现。 在站点上添加“返回顶部”按钮是改善站点导航的一种好方法,尤其是当您具有长滚动页面或无限滚动功能时。
扩展
使用“返回顶部”按钮可使滚动浏览内容的用户快速返回页面顶部。当用户开始滚动页面时,该按钮就会出现,并且该页面会保留在您网站上的固定位置,以便用户在滚动过程中可以看到该按钮。
在网站中添加这个功能有两种方式:使用插件或者编写自定义代码。今天我们主要讲如何自己编写一个返回顶部的功能。
编写JS返回动画
jQuery( document ).ready(function($){
var offset = 100,
speed = 250,
duration = 500,
scrollButton = $('#topbutton');
$( window ).scroll( function() {
if ( $( this ).scrollTop() < offset) {
scrollButton.fadeOut( duration );
} else {
scrollButton.fadeIn( duration );
}
});
scrollButton.on( 'click', function(e){
e.preventDefault();
$( 'html, body' ).animate({
scrollTop: 0
}, speed);
});
});
将这段代码保存为top.js放在你的目录下。
定义返回顶部功能
/**
* 调用Js动画
*/
function themeslug_add_button_script() {
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/assets/js/minified/top.js', array( 'jquery' ),false, true);
}
add_action( 'wp_enqueue_scripts', 'themeslug_add_button_script' );
/**
* 网页添加返回按钮
*/
function themeslug_add_scroll_button() {
echo '<a href="#" id="topbutton"></a>';
}
add_action( 'wp_footer', 'themeslug_add_scroll_button' );
将此段代码复制到主题的functions.php中,也可以使用Code Snippets来使用这段代码
相应的按钮样式
#topbutton {
position: fixed;
display: none;
height: 40px;
width: 40px;
line-height: 40px;
right: 15px;
bottom: 15px;
z-index: 1;
background: #000000;
border-radius: 2px;
text-decoration: none;
color: #ffffff;
text-align: center;
}
#topbutton:after {
content: "\25B2";
}
具体效果可以看我的演示站。