層的移動本來很簡單,用jquery插件或者自己寫一個也不難,但是最近一個ipad項目里,發現用手移動div會感覺很卡,體驗很差(可能是ipad的配置根不上pc)。
同樣如果一個頁面結構很復雜或者電腦配置不好的話也會出現這種情況。為了弄清變慢的原因,我們做了幾個demo對比,最后發現在mousemove事件上加上定時器能改進這個體驗。
整個代碼的關鍵地方在于當鼠標按下時開始了的計時器,這樣Onmousemove事件會每隔30ms執行一次,然后在鼠標松下的時候清除計時器。
timer=setInterval(function(){flag=true;},30);
這樣可以減輕瀏覽器繪制div層的負擔,不至于拖動時每時每刻都在移動,其實太短了人眼也感覺不到變化,延遲間隔可以自己根據體驗設置。
function Endrag(source,target){source=typeof(source)=="object" ? source:document.getElementById(source);target=typeof(target)=="object" ? target:document.getElementById(target);var x0=0,y0=0,x1=0,y1=0,moveable=false,index=100;var timer,flag=false;var i=0;source.onmousedown=function(e){e = e ? e : (window.event ? window.event : null);x0 = e.clientX ;y0 = e.clientY ;x1 = isNaN(parseInt(source.style.left))?0:parseInt(source.style.left);y1 = isNaN(parseInt(source.style.top))?0:parseInt(source.style.top);moveable = true;//當鼠標按下時,定時器開始工作,每隔50ms執行一次mousemove事件timer=setInterval(function(){flag=true;},30);};//拖動;source.onmousemove=function(e){e = e ? e : (window.event ? window.event : null);if(moveable){if(flag){i++;flag=false;target.style.left = (e.clientX + x1 - x0 ) + "px";target.style.top = (e.clientY + y1 - y0 ) + "px";}}};//停止拖動;source.onmouseup=function (e){if(moveable) {moveable = false;clearInterval(timer);//alert(i);}};//停止拖動;source.onmouseout=function (e){if(moveable) {moveable = false;clearInterval(timer);//alert(i);}};}
新聞熱點
疑難解答