10-錨點定位/滾動條定位到指定位置/動畫效果/scrollIntoView/wowjs


需求:(vue項目)

導航固定,導航上錨點定位,滾動條滾動有動畫效果。


 實現方法:

1)最簡單的莫過於用a標簽的href="#要跳轉的id名"即可,不過這種會造成頁面的刷新

2)用 scrollIntoView()來做,不過這個api是相對於瀏覽器頂部對齊的。由於我們的導航是固定定位,那么在進行滾動的時候,導航會蓋着模塊的部分內容(導航高度),就導致我們看起來好像錨點定位的不准確。這點是弊病

3)有了上面的問題,我們需要自己手動去給到滾動位置,自己去計算;並且加上滾動動畫效果

document.documentElement.scrollTop = 100 // 設置滾動條距離瀏覽器頂部的距離  這就是核心代碼

但是這樣是很生硬的就滾動到了我們要去的位置,我們需要實現一個動畫效果:

// 滾動條滾動位置及動畫函數封裝 /** * @param {*} number 距離頂部的距離(Number類型) * @param {*} time 滾動用時(Number類型) * @returns */ export const scrollToAnimationFn = (number = 0, time) => { if (!time) { document.body.scrollTop = document.documentElement.scrollTop = number return number } const spacingTime = 20 // 設置循環的間隔時間 值越小消耗性能越高
  let spacingInex = time / spacingTime // 計算循環的次數
  let nowTop = document.body.scrollTop || document.documentElement.scrollTop // 獲取當前滾動條位置
  const everTop = (number - nowTop) / spacingInex // 計算每次滑動的距離
  const scrollTimer = setInterval(() => { if (spacingInex > 0) { spacingInex-- scrollToAnimationFn((nowTop += everTop)) } else { clearInterval(scrollTimer) // 清除計時器
 } }, spacingTime) }

使用:下圖中的50,86,16 分別是header的高度,導航的高度,marginTop


 除了之上的基本要求外,我們還可以用wowjs進行錨點滾動到指定模塊后,模塊顯示的動畫效果

WOW.js 是一款幫助你實現滾動頁面時觸發CSS 動畫效果的插件。

animate使用說明

項目中使用:

main.js中:

// 動畫 animate.css
  import '../node_modules/wowjs/node_modules/animate.css/animate.min.css'
// 滾動動畫 wow.js
import { WOW } from 'wowjs' Vue.prototype.$wow = new WOW({ boxClass: 'wow', // default
  animateClass: 'animated', // default
  offset: 150, // default
  mobile: true, // default
  live: false, // live為true時,控制台會提示:MutationObserver is not supported by your browser. & WOW.js cannot detect dom mutations, please call .sync() after loading new content.
 callback: function (box) { console.log('WOW: animating <' + box.tagName.toLowerCase() + '>') } })

具體組件中:

(1) 初始化

 

(2) 結構中

  即可!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM