JavaScript原生折叠扩展收缩菜单带缓冲动画 @落雨
/** * 展开与收缩 * @param {[type]} ObjectId [description] 需要操作的ID * @param {[type]} me [description] 当前对象,非必须 * @return {[type]} [description] */function spread(ObjectId, me) { var img = me.getElementsByTagName('img')[0]; if ($X(ObjectId).style.display == 'none') { me.style.color = '#34a8bf'; Start(ObjectId, 'Opens'); //替换右边小图标 img.src="img/show_btn1.png"; } else { me.style.color = '#000'; Start(ObjectId, 'Close'); img.src="img/show_btn.png"; }}/** * 根据ID返回对象 * @param {[type]} Read_Id [description] * @return {[type]} [description] */function $X(Read_Id) { return document.getElementById(Read_Id);}/** * 开始动画+收缩啊啊啊啊啊啊啊啊 * @param {[type]} ObjId [description] * @param {[type]} method [description] */function Start(ObjId, method) { var oo = $X(ObjId); var firstH = oo.offsetHeight; //获取对象高度 firstH = firstH == 0 ? '300px' : firstH; if (method == "Close") { startrun(oo, "height", 0, function() { oo.style.display = "none"; }, 'close'); } else if (method == "Opens") { oo.style.display = "block"; oo.style.height = 0; startrun(oo, "height", 300, function() { }, 'close'); //oo.style.height = firstH; }}/** * 获得Style属性 * @param {[type]} obj [description] * @param {[type]} name [description] * @return {[type]} [description] */function getstyle(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; } else { return getComputedStyle(obj, false)[name]; }}/** * 动画库 * @param {[type]} obj [description] * @param {[type]} attr [description] * @param {[type]} target [description] * @param {Function} fn [description] * @param {[type]} action [description] * @return {[type]} [description] */function startrun(obj, attr, target, fn, action) { clearInterval(obj.timer); obj.timer = setInterval(function() { var cur = 0; obj.style.overflow = 'hidden'; if (attr == "opacity") { cur = Math.round(parseFloat(getstyle(obj, attr)) * 100); } else { cur = parseInt(getstyle(obj, attr)); } var speed = (target - cur) / 8; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if (cur == target) { clearInterval(obj.timer); if (fn) { fn(); } } else { if (attr == "opacity") { obj.style.filter = "alpha(opacity=" + (cur + speed) + ")"; obj.style.opacity = (cur + speed) / 100; } else { obj.style[attr] = cur + speed + "px"; } } if (action == 'open') { //obj.style.display = "block"; } else { //obj.style.display = "none"; } }, 30)}