div层的移动及性能优化_Javascript教程-查字典教程网
div层的移动及性能优化
div层的移动及性能优化
发布时间:2016-12-30 来源:查字典编辑
摘要:同样如果一个页面结构很复杂或者电脑配置不好的话也会出现这种情况。为了弄清变慢的原因,我们做了几个demo对比,最后发现在mousemove事...

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

}

};

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新Javascript教程学习
    热门Javascript教程学习
    编程开发子分类