[WordPress] 浮動式上下篇文章按鈕

2016-12-01

今天稍早前透過wordpress中wp-includes/link-template.php->get_the_post_navigation的方法實作了上下篇文章的連結,透過一些CSS與javascript的語法來達成此項功能。

完成結果如下圖(預設文字框為隱藏)

[WordPress] 浮動式上下篇文章按鈕 Demo圖

wp主題functions.php
<?php
function call_post_navigation(){
?>
<script>
$(document).ready(function() {
    $(".nav-next").hover(function(){
        $(this).find("img").attr("src","/images/next_48_on.png");
    },function(){
        $(this).find("img").attr("src","/images/next_48_of.png");
    });
    $(".nav-previous").hover(function(){
        $(this).find("img").attr("src","/images/prev_48_on.png");
    },function(){
        $(this).find("img").attr("src","/images/prev_48_of.png");
    });
});
</script>
<?php 
}
?>

這邊是滑鼠放置到按鈕圖片上與浮動區塊上的監聽(圖片的src可自行替換)

wp主題single.php
//此區塊放置文章外
<?php call_post_navigation(); ?>
//此區塊放置文章中
<?php
    the_post_navigation(array(
        'next_text' => '<img src="/images/next_48_of.png" /><div class="post-navigation-div"><div class="post-navigation-title">下一篇文章</div><div class="post-navigation-memo">%title</div></div>',
        'prev_text' => '<div class="post-navigation-div"><span class="reader-text"><div class="post-navigation-title">上一篇文章</div><div class="post-navigation-memo">%title</div></div><img src="/images/prev_48_of.png" />',
    ));
?>

配置上下篇文章的版面,類別與圖片可自行替換

wp主題style.css或自訂style
/*
 *post-navigation
 */
.post-navigation {
 width: 1710px;
 position: fixed;
 left: 0;
 right: 0;
 top: 45%;
 margin: 0 auto;
}
.nav-links a {
 text-decoration: none;
}
.nav-links a:hover .post-navigation-div {
 opacity: 1;
}
.nav-previous {
 width: 269px;
 float: left;
}
.nav-previous a img {
 float: right;
 padding-left: 9px;
}
.nav-next {
 width: 269px;
 float: right;
}
.nav-next a img {
 float: left;
 padding-right: 9px;
}
.screen-reader-text {
 display: none;
}
.post-navigation-div {
 width: 205px;
 background: #F5F5F5;
 border: solid 1px #ffffff;
 position: relative;
 top: 0px;
 z-index: 3;
 padding: 2px;
 overflow: hidden;
 color: #333;
 box-shadow: 0px 0px 10px #666;
 float: left;
 opacity: 0;
 transition: all 0.5s;
}
.post-navigation-title {
 padding: 4px 0px;
 background: #565656;
 color: #FFF;
 text-align: center;
}
.post-navigation-memo {
 text-align: center;
 width: 95%;
 margin: 5px auto 3px auto;
 line-height: 22px;
}
/*
 *RWD代碼寬度1745px以下不顯示浮動式按鈕,改成放置到呼叫the_post_navigation的地方
 */
@media screen and (max-width: 1745px){
 .nav-previous {
 width: 50%;
 }
 .nav-previous img {
 display: none;
 }
 .nav-next {
 width: 50%;
 }
 .nav-next img {
 display: none;
 }
 .post-navigation {
 width: 100%;
 position: relative;
 margin: 0 auto 10px auto;
 display: inline-block;
 }
 .post-navigation-div {
 width: 90%;
 float: none;
 opacity: 1;
 margin: 0 auto;
 }
}

這邊定義了一些懸浮框的樣式,如有需要可自行修改。

比較需要注意的是1745px以下解析度的螢幕便不會顯示浮動式按鈕,改為顯示在放置get_the_post_navigation的地方,當然有需要的可以去調整CSS與javascript讓浮動按鈕可以左右對齊好。

分類