首页 问答 正文

如何为wordpress网站添加回到顶部按钮?

注册会员 / 悠然自学 / 2023-06-11/ 浏览 141 次

为WordPress网站添加回到顶部按钮可以使用以下步骤:

  1. 在主题的functions.php文件中添加以下代码:
function add_scroll_to_top_button() {
  echo '<a href="#top" class="scroll-to-top"><i class="fa fa-chevron-up"></i></a>';
}

add_action('wp_footer', 'add_scroll_to_top_button'); 
  1. 在CSS文件中添加以下代码:
.scroll-to-top {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: black;
  color: white;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  text-align: center;
  line-height: 50px;
  z-index: 9999;
}

.scroll-to-top:hover {
  background: #666;
} 
  1. 添加以下JavaScript代码:
jQuery(document).ready(function($) {
  $(window).scroll(function() {
    if ($(this).scrollTop() > 200) {
      $('.scroll-to-top').fadeIn();
    } else {
      $('.scroll-to-top').fadeOut();
    }
  });

  $('.scroll-to-top').click(function(e) {
    e.preventDefault();
    $('html, body').animate({scrollTop: 0}, 800);
  });
}); 

这样,当用户向下滚动页面时,回到顶部按钮将会出现,当用户点击按钮时,页面将平滑滚动到页面的顶部。

大家谈论
    我的见解