關(guān)于吸頂
吸頂效果在使得用戶在滑動(dòng)讀取數(shù)據(jù)的時(shí)候把產(chǎn)品需要持續(xù)展示的控件及信息一直固定在屏幕上方,以便用戶操作和交互。
產(chǎn)生背景
??隨著技術(shù)不斷更新與用戶審美不斷提升,一些App中/瀏覽器中的常用交互也在對(duì)用戶更加友好,在某些數(shù)據(jù)展示較多頁面或者導(dǎo)航欄頁面,為了將欄目劃分,使得視圖模塊更加明顯,吸頂效果便在此背景下孕育而生。
??那么,我們?nèi)绾卧趙eb端來做一個(gè)吸頂效果呢?
切入正題——吸頂
簡單效果展示

吸頂.gif
上方數(shù)據(jù)
- 需要吸頂?shù)脑?br>
- 吸頂下方數(shù)據(jù)
- 接著我們邏輯走一下:(我們?cè)O(shè)吸頂元素為X)
- 在頁面滑動(dòng)距離 <= 吸頂元素距離頂端距離時(shí),不吸頂
- 否則,吸頂
- 有了這個(gè)大前提,繼續(xù)考慮,如何做到吸頂呢?
- 設(shè)置該元素的position為fixed屬性
- 動(dòng)態(tài)控制是否展示該樣式
- 擴(kuò)展:加點(diǎn)動(dòng)畫效果(這里以漸變?yōu)槭纠?
代碼及注釋
// html
<template>
<div class="scrollFixed">
<!-- 上方數(shù)據(jù) -->
<div class="sTop">
<ul>
<li v-for="(ietm, index) in 10">這是吸頂上方的第{{index + 1}}條數(shù)據(jù)</li>
</ul>
</div>
<!-- 吸頂元素 -->
<nav class="nav" id="searchBar" :class="scrollFixed === true ? 'isFixed' :''">{{ text }}</nav>
<!-- 下方數(shù)據(jù) -->
<div class="sBottom">
<ul>
<li v-for="(ietm, index) in 30">這是吸頂下方的第{{index + 1}}條數(shù)據(jù)</li>
</ul>
</div>
</div>
</template>
// js
<script>
export default {
data() {
return {
text: '需要吸頂',
scrollFixed: false,
offsetTop: 0
}
},
methods: {
windowScroll () {
// 滾動(dòng)條頂部 距 滾動(dòng)原點(diǎn)的高度
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
/**
* 三目運(yùn)算
* 兩個(gè)高度比較
* 如果滑動(dòng)距離 > 吸頂元素到頁面頂端距離 動(dòng)態(tài)添加
*/
scrollTop >= this.offsetTop ? (this.scrollFixed = true, this.text = '已吸頂') : (this.scrollFixed = false, this.text = '需要吸頂');
}
},
mounted() {
// 需吸頂元素 距 離瀏覽器頂端的高度
this.offsetTop = document.querySelector('#searchBar').offsetTop;
// 滾動(dòng)監(jiān)聽
window.addEventListener('scroll', this.windowScroll);
},
destroyed () {
// 關(guān)閉 銷毀監(jiān)聽
window.removeEventListener('scroll', this.windowScroll);
}
}
</script>
<style scoped type="text/scss" lang="scss">
.isFixed{
position:fixed;
top:0;
left: 0;
z-index:999;
background: #12d168;
transition: all 1s;
color: #7511ff;
}
// 基本樣式略
// ......
</style>
備注
??此demo在流行瀏覽器中運(yùn)行問題不大,但是沒有詳測(cè)兼容性。如果要在生產(chǎn)上運(yùn)用,務(wù)必做好各端兼容。