首页 问答 正文

如何为WordPress站点添加阅读进度条?

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

要为WordPress站点添加阅读进度条,通常可以使用插件或手动添加代码。

一种常见的插件是Nanobar,它可以在页面的顶部或底部显示一个细条,以显示页面的阅读进度。安装并启用该插件后,可以在插件设置中选择进度条的位置和颜色。

如果想手动添加代码,可以使用JavaScript和CSS创建自定义阅读进度条。以下是一个示例代码:

在主题的functions.php文件中添加以下函数:

function add_read_progress_bar() {
    wp_enqueue_script( 'read-progress-bar', get_template_directory_uri() . '/js/read-progress-bar.js', array( 'jquery' ), '1.0', true );
    wp_enqueue_style( 'read-progress-bar', get_template_directory_uri() . '/css/read-progress-bar.css' );
}
add_action( 'wp_enqueue_scripts', 'add_read_progress_bar' ); 

在主题的js文件夹中创建一个名为read-progress-bar.js的文件,并添加以下代码:

jQuery(document).ready(function($) {
    /* Hide the progress bar on page load */
    $("body").append("<div class='read-progress-bar'><div class='read-progress-bar__bar'></div></div>");
    $(".read-progress-bar").hide();
    /* Show the progress bar when the page is scrolled */
    $(window).scroll(function() {
        var scrollPosition = $(window).scrollTop();
        var windowHeight = $(window).height();
        var documentHeight = $(document).height();
        var progress = scrollPosition / (documentHeight - windowHeight) * 100;
        $(".read-progress-bar__bar").css("width", progress + "%");
        $(".read-progress-bar").show();          
    });
}); 

在主题的css文件夹中创建一个名为read-progress-bar.css的文件,并添加以下代码:

.read-progress-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 5px;
    z-index: 999;
}
.read-progress-bar__bar {
    height: 5px;
    background-color: #0074b9;
} 

这些代码会创建一个蓝色的进度条,在页面上部分显示,当用户滚动内容时,进度条会逐渐展示。

大家谈论
    我的见解