本章集中介紹四個重要的小功能:回到頂部浮動按鈕、矢量圖標、頁腳沉底和粘性側邊欄。
這幾個功能與Django基本沒啥關係,更多的是前端知識,但是對博客網站都很重要,問的讀者也比較多,因此也集中講一下好了。
回到頂部浮動按鈕
當用戶拜讀完你的博文後,可能想回到文章開頭重新閱讀,或者審視其中的某些內容。如果文章內容較多,不停滑動滾輪迴頁面頂部未免有點太讓人煩躁了。
一種解決辦法是增加一個回到頂部的浮動按鈕。當頁面向下滾動到某個位置後,按鈕就呈現在頁面右下角;點擊按鈕,頁面就回到頂部。這個功能 Bootstrap 4 似乎沒有提供,但也不複雜,就自己用 JavaScript 和 CSS 寫吧。
在templates
目錄新建back_to_top_func.html
文件,寫入以下代碼:
templates/back_to_top_func.html
<!-- 參考了 鸚鵡 的代碼,在此致謝 -->
<!-- https://ezbox.idv.tw/131/back-to-top-button-without-images -->
<button type="button" id="BackTop" class="toTop-arrow" style="z-index: 100;"></button>
<script>
// 向上滾動的函數
$(function () {
$(#BackTop).click(function () {
$(html,body).animate({scrollTop: 0}, 500);
});
$(window).scroll(function () {
if ($(this).scrollTop() > 300) {
$(#BackTop).fadeIn(300);
} else {
$(#BackTop).stop().fadeOut(300);
}
}).scroll();
});
</script>
<style>
/* 按鈕邊框的大小、位置、樣式 */
.toTop-arrow {
width: 3.5rem;
height: 3.5rem;
padding: 0;
margin: 0;
border: 0;
border-radius: 33%;
opacity: 0.7;
background: black;
cursor: pointer;
position: fixed;
right: 1.5rem;
bottom: 1.5rem;
display: none;
}
/* 繪製按鈕中的向上箭頭 */
.toTop-arrow::before, .toTop-arrow::after {
width: 31px;
height: 7px;
border-radius: 3px;
background: orange;
position: absolute;
content: "";
}
.toTop-arrow::before {
transform: rotate(-45deg) translate(0, -50%);
left: 0.4rem;
}
.toTop-arrow::after {
transform: rotate(45deg) translate(0, -50%);
right: 0.4rem;
}
/* 取消點擊按鈕時的聚焦 */
.toTop-arrow:focus {
outline: none;
}
</style>
代碼分成html
、javascript
、css
三部分。
HTML部分只有一行,用button標籤表示了浮動按鈕的容器。
JavaScript部分主要用到了Jquery的語法。頁面載入完成後開始監聽兩個事件:
- 當用戶點擊浮動按鈕時,將頁面滾動到頂部
- 當頁面滾動時,根據頁面距離頂部的距離,決定按鈕顯示或隱藏
CSS部分最長但也很簡單,主要定義了按鈕的位置、大小、圖案等樣式。讀者可以試著、改動、刪除部分代碼,看看按鈕形態會怎樣變化。
核心代碼就寫好了。有點小瑕疵的是前面在footer.html
中定義了class="fixed-bottom"
,這個屬性的顯示層級很高,會將浮動按鈕給覆蓋掉。因此刪除templates/footer.html
中的fixed-bottom
屬性:
templates/footer.html
...
<!-- 刪除了 fixed-bottom 屬性 -->
<footer class="py-3 bg-dark">
...
</footer>
z-index這個css樣式決定了頁面中容器的顯示順序,數值越大則顯示優先順序越高。
之所以fixed-bottom會覆蓋掉浮動按鈕,就是因為它將z-index設置成了一個很大的數值。
因為我們想在全站都擁有這個按鈕,所以將剛寫好的模塊引用到base.html
中:
templates/base.html
...
<body>
...
<!-- jquery.js -->
<script src="{% static jquery/jquery-3.3.1.js %}"></script>
...
<!-- 在jquery後面引入 -->
{% include back_to_top_func.html %}
</body>
...
注意模塊用到了Jquery,因此要在Jquery後面引入。
效果如下: