纯代码实现 WordPress 文章阅读进度条

要纯代码实现 WordPress 文章阅读进度条,你可以按照以下步骤进行操作:

在主题的 functions.php 文件中添加必要的 JavaScript 和 CSS:

function custom_read_progress_bar_scripts() {
   wp_enqueue_script('jquery');
   wp_enqueue_script('readprogressbar', get_template_directory_uri() . '/js/readprogressbar.js', array('jquery'), '1.0', true);
   wp_enqueue_style('readprogressbarstyle', get_template_directory_uri() . '/css/readprogressbar.css');
}
add_action('wp_enqueue_scripts', 'custom_read_progress_bar_scripts');

创建一个 JavaScript 文件(readprogressbar.js):

在你的主题文件夹中创建一个名为 js 的文件夹,然后在其中创建 readprogressbar.js 文件,添加以下代码:

jQuery(document).ready(function($) {
   $(window).scroll(function() {
       var scrollDistance = $(window).scrollTop();
       var documentHeight = $(document).height();
       var windowHeight = $(window).height();
       var scrollPercentage = (scrollDistance / (documentHeight  windowHeight))  100;
       $('#readprogressbar').css('width', scrollPercentage  '%');
   });
});

创建一个 CSS 文件(readprogressbar.css):

在你的主题文件夹中创建一个名为 css 的文件夹,然后在其中创建 readprogressbar.css 文件,添加以下代码:

#readprogresscontainer {
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
   height: 3px;
   backgroundcolor: #0073e6; / 进度条颜色 /
   zindex: 9999;
}
 
#readprogressbar {
   height: 100%;
   width: 0;
   backgroundcolor: #ff6600; / 进度条背景颜色 /
}

在文章模板中添加 HTML 代码:

在你的 WordPress 主题的单篇文章模板(通常是 single.php)中,添加以下 HTML 代码来显示进度条:

<?php custom_read_progress_bar_scripts() ?>

保存并激活主题:

确保你的主题文件夹中包含了上述的 JavaScript 和 CSS 文件,然后保存并激活主题。

现在,当用户滚动浏览文章时,将显示一个进度条,以显示他们已经阅读的文章部分。你可以根据需要自定义进度条的颜色和样式。

您可能还喜欢
发表评论

本网站使用Cookie来改善您的体验。我们假设您对此没有异议,请点接受同意本协议,否则选择退出。 接受 阅读更多