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) 结构中

  即可!

 

posted @ 2022-02-18 14:02  猎奇游渔  阅读(2511)  评论(0编辑  收藏  举报