给WordPress网站添加返回顶部按钮

代码版方法

代码版网上搜索会有很多种方法,这里只分享使用代码实现的方法.

首先,新建一个名为back-to-top.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);
  });
});

你也可以点击这里从github直接下载(可能需要袋里才能打开).新建好之后,把js文件上传到你主题文件的js目录下。然后引用这个js文件,方法有两种,一种是主题函数里面引用,另外一种是自己添加到网站主题页脚文件.主题函数引用的话,在函数文件functions.php里面插入下面这串代码。

/**
 * 引用JS文件
 */
function themeslug_add_button_script() {
  wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . 'https://yourdomain.com/js/back-to-top.js', array( 'jquery' ) );
}
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' );

修改页脚文件引用的话,在footer.php里面,插入下面的代码。

<a href="#" id="topbutton"></a>
<script type='text/javascript' src="https://yourdomain.com/wp-content/themes/twentytwelve/js/back-to-top.js "></script>

上面代码中的https://yourdomain.com/wp-content/themes/twentytwelve/js/back-to-top.js请修改成你自己的实际地址。

最后是添加css样式

在主题的css文件style.css里面,添加下面的代码:

#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: "\2191";
}

一切搞定后,前台刷新就可以看到效果了。

可能你的按钮是一个“↑”符号,如果要变成▲就把\2191修改为\25B2就好了。