経緯
フロント何もわからんない...OSSにコントリビュートして武者修行してみよう。
要件
1度何となく作ってPR出してみたら「要件不足してたから定義するね」って言ってくれた。優しい。詳細は以下。
- At the top of the page the header has full opacity (as it does in your case)
- The user scrolls down -> the header disappears completely (0.0 opacity)
- The user scrolls up -> the header appears, and if the page isn't at the top then we'd have an opacity of 0.5 or - so for just the background of the header
- The logo and buttons would have full opacity, just the background would be a bit transparent
実装
内容は英文の通りなので割愛。
- opacityで実装しようとしていたんだけど、opacityは強制的に子も親の値を継承してしまうらしい。
- ヘッダー上に描画されるボタン類(子要素)も一緒に透明化してしまっていた。
- そんなときはrgbaのaで調整すればいいとのこと。参考
- スクロール時のoffsetを常にキャッチ。更新前の値と比較して、スクロールダウン、アップに応じてheaderOpacityを更新する。
vue.js
<template>
<header
ref="header"
class="header-container sticky top-0 z-10 drop-shadow-md"
:style="{
'background-color': `rgba(22, 27, 34,${headerOpacity})`,
}"
>
<div>
〜省略〜
</div>
</header>
</template>
<script lang="ts">
import { Ref } from "vue";
export default {
setup() {
const headerOpacity: Ref<number> = ref(1);
const prevScrollY: Ref<number> = ref(0);
onMounted(() => {
window.addEventListener("scroll", handleScroll);
});
onUnmounted(() => {
window.removeEventListener("scroll", handleScroll);
});
function handleScroll(): void {
const scrollY: number = window.scrollY;
if (scrollY > 0) {
if (scrollY > prevScrollY.value) {
headerOpacity.value = 0;
} else headerOpacity.value = 0.5;
} else {
headerOpacity.value = 1;
}
prevScrollY.value = scrollY;
}
return { headerOpacity };
},
};
</script>
<style scoped>
.header-container {
transition: 1s;
}
</style>
prevScrollY(直前のスクロール値)はどうやって管理した方がいいのだろうか(´・ω・`)
追記
スクロール量のモニタリングは標準で備わっているwatchを利用した方がいいのでは?とのコメントをいただきました!
仰る通りだと思います!ありがとうございます!