在web 2.0时代里,渐变效果无处不在,元素高的渐变效果也经常可见,下面我写了一个渐变高的js类 原理很简单:就是构造一个定时器,不断改变元素的高度 style.height 代码分以下几步: 1. 变量初始化initialize() 2. 开始执行程序start() 3. 构造一个定时器 run() 4. 设置高度setHeight() 5. 获取步长 getV() ------------------------------------------------------------------ 代码如下 var isIE = (document.all) ? true : false; var $ = function (id) {return "string" == typeof id ? document.getElementById(id) : id;}; if(!isIE){ HTMLElement.prototype.__defineGetter__("currentStyle", function () { return this.ownerDocument.defaultView.getComputedStyle(this, null); }); } var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } } Object.extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; } var fadeStruct = function(options){ this.start = 0;//开始值 this.end = 0;//结束值 this.current = 0;//当前值 Object.extend(this, options || {}); } /* 渐变高类 author: 选择多灵活多 */ var eyejsFadeHeight=Class.create(); eyejsFadeHeight.prototype.initialize=function(id){ this._container=$(id); this._time=5; this._show=true; this._finish=true; this.Step=4; //步长越大,效果越明显 this._yBorder = function(){ return ( parseInt($(id).currentStyle.borderTopWidth) + parseInt($(id).currentStyle.borderBottomWidth) ); } //在IE下,如果元素无边框时,this._yBorder()会是NaN,而FF是0 this._borderTBWidth=isNaN(this._yBorder())?0:this._yBorder(); this._objH=new fadeStruct({start:0,end:$(id).offsetHeight-this._borderTBWidth }); } eyejsFadeHeight.prototype.start=function(){ this._show = !this._show; if(this._show){ this._objH.current = this._objH.end;} else{ this._objH.current = this._objH.start; } this.run(); } eyejsFadeHeight.prototype.run=function(){ var _oThis=this; this._finish = true; this.setHeight(); if(this._finish) return; else setTimeout(function(){_oThis.run();},_oThis._time); } eyejsFadeHeight.prototype.setHeight=function(){ var iGet = this.getV(this._objH, this._container.offsetHeight - this._borderTBWidth); if(isNaN(iGet)) return true; this._container.style.height = iGet + "px"; return false; } //获取设置值 eyejsFadeHeight.prototype.getV=function(o,nowV){ /*var vH=(o.current - nowV) / this.Step+nowV; if(o.current!=vH) this._finish = false; return vH;*/ var iStep = (o.current - nowV) / this.Step; if(iStep){ this._finish = false; if(Math.abs(iStep) < 1){ iStep = iStep > 0 ? 1 : -1; } return nowV + iStep; } } height.rar(1.86 KB)