div层的移动及性能优化

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

div层的移动及性能优化

  2020-05-12 我要评论
同样如果一个页面结构很复杂或者电脑配置不好的话也会出现这种情况。为了弄清变慢的原因,我们做了几个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);
}
};
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们