# vue 回到最頂部 網頁通常在右下角 會有個可以快速滑至頂部的top按鈕 --- #### 按鈕外觀 - style框架使用Tailwind - vue的transition動畫 css要另外寫 ``` javascript= <template> <Transition name="fade"> <div v-if="isShow" class="fixed right-4 bottom-4"> <div class="p-2.5 rounded-sm bg-accent-success text-primary-lg hover:bg-accent-y cursor-pointer transition" @click="scrollTop"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5" > <path stroke-linecap="round" stroke-linejoin="round" d="M12 19.5v-15m0 0l-6.75 6.75M12 4.5l6.75 6.75" /> </svg> </div> </div> </Transition> </template> ``` #### 程式 ``` javascript= export default { name: 'ScrollTopBtn', data () { return { elTop: 0, // 滾動前,捲軸距離視窗頂部的距離 isShow: false } }, mounted () { window.addEventListener('scroll', this.scrolling) // 資料掛載完, window去監聽scroll事件 }, methods: { // 要滑到top為0的位置, 使用smooth的模式 scrollTop () { window.scrollTo({ top: 0, behavior: 'smooth' }) }, scrolling () { // 捲軸距離視窗頂部的距離 const scrolltoTop = window.pageYOffset // 捲軸滾動的距離 const scrollLength = scrolltoTop - this.elTop // 更新: 滾動前,捲軸距離視窗頂部的距離 this.elTop = scrolltoTop // 判斷想要什麼高度讓按鈕出現 if (scrollLength < 0 && this.elTop < 200) { this.isShow = false } else { this.isShow = true } } } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up