動畫很炫, 但是在IE上使用反而有點小問題, 問Google也沒有相關資料, 為什麼沒人有遇到相同的困惱呢?
slideDown執行上沒有問題, 在縮小(slideUp)時, 當height等於零, 反而會顯示全部內容, 但是畫面閃一下, 內容又被隱藏了。
線上展示(限IE瀏覽, 不然看不出問題點)
為了這個小問題又殺進JQuery內部去了解animate,
研究心得整理, 要製作動畫需考量改變屬性、重覆執行及變化速度控制
改變屬性:
除了高度(height), 寬度(width), 透明度(opacity)之外, JQuery在
高度變化增加了marginTop, marginBottom, paddingTop, paddingBottom屬性,
寬度變化增加了marginLeft, marginRight, paddingLeft, paddingRight屬性
fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ];
重覆執行:setInterval(重覆執行, 直到clearInterval清除), setTimeout(只執行一次, 要重覆使用)。
timerId = setInterval(jQuery.fx.tick, 13);
變化速度控制:利用時間變化比率來改變, JQuery每13毫秒執行一次, 示意程式碼如下。
timeRate(600,function(r){ document.write(''+r+''); }); function timeRate(step,fn){ var t = now(); var timeId = setInterval(function(){ var t1 = now(); var rate = ((t1-t)>step) ? 1 : (t1-t)/step; fn(rate); if(rate==1){clearInterval(timeId);} },13); } function now() { return (new Date).getTime(); }
結果問題在於動畫完成的最後是執行隱藏物件, 將物件display屬性設為none
如果是直接執行是沒有問題, 但是它卻是透過setInterval來執行, 反而造成時間差, 才會有閃一下的情況發生。
解決方案
改變它:jQuery.fx.step是實際執行的函數, 變更相關參數後, 再執行jQuery.fx.update改變物件屬性。
var n = t - this.startTime; var dur = this.options.duration; this.state = n / dur; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation //this.update(); if(this.now<1){ this.step(true); }else{ this.update(); }
自己做
var b1 = new slide_fix($('#Div3')); $('#Button5').click(function(){b1.close();});//收 $('#Button6').click(function(){b1.open();});//開 function slide_fix(b){ var h = b.height(); var step = 600; var time = 13; this.open = function(){ timeRate(step,function(c,r){ var h1 = h*r; b.height(h1); if(c==1){b.show();} }); } this.close = function(){ timeRate(step,function(c,r){ var h1 = h *(1-r); b.height(h1); if(r==1){b.hide();} }); } function timeRate(step,fn){ var t = now(); var count = 1; var timeId = setInterval(function(){ var t1 = now(); var rate = ((t1-t)>step) ? 1 : (t1-t)/step; fn(count,rate); if(rate==1){clearInterval(timeId);} count++; },time); } function now() { return (new Date).getTime(); } }
以上~~希望對你有幫助