143行js顶部进度条最小插件-nanobar.js源码解析

这篇博客探讨了nanobar.js,一个仅143行的JavaScript顶部进度条插件。作者通过分析源码,揭示了其利用DOM和JS原生选择器创建动态元素,通过设置width实现动画效果的工作原理。文章详细讲解了构造函数NanoBar、init()方法以及go方法背后的动画机制,展示了如何通过CSS和JavaScript协同实现平滑的动画过渡效果。

网页顶部进度条插件的有四五种,基本原理就是动态地创建一个元素,然后通过设置它的width来实现动画效果,width增长到达指定位置时,将其去掉。
来看看nanobar.js作者jacoborus是怎么做到的吧!

/* http://nanobar.micronube.com/  ||  https://github.com/jacoborus/nanobar/    MIT LICENSE */
(function (root) {
   
   
  'use strict'
  // container styles
  var css = '.nanobar{width:100%;height:4px;z-index:9999;top:0}.bar{width:0;height:100%;transition:height .3s;background:#000}'

  // add required css in head div
  function addCss () {
   
   
    var s = document.getElementById('nanobarcss')

    // check whether style tag is already inserted
    if (s === null) {
   
   
      s = document.createElement('style')
      s.type = 'text/css'
      s.id = 'nanobarcss'
      document.head.insertBefore(s, document.head.firstChild)
      // the world
      if (!s.styleSheet) return s.appendChild(document.createTextNode(css))
      // IE
      s.styleSheet.cssText = css
    }
  }

  function addClass (el, cls) {
   
   
    if (el.classList) el.classList.add(cls)
    else el.className += ' ' + cls
  }

  // create a progress bar
  // this will be destroyed after reaching 100% progress
  function createBar (rm) {
   
   
    // create progress element
    var el = document.createElement('div'),
        width = 0,
        here = 0,
        on = 0,
        bar = {
   
   
          el: el,
          go: go
        }

    addClass(el, 'bar')

    // animation loop
    function move () {
   
   
      var dist = width - here

      if (dist < 0.1 && dist > -0.1)</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值