网页顶部进度条插件的有四五种,基本原理就是动态地创建一个元素,然后通过设置它的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)</

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

1762

被折叠的 条评论
为什么被折叠?



