手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >div层的移动及性能优化
div层的移动及性能优化
摘要:同样如果一个页面结构很复杂或者电脑配置不好的话也会出现这种情况。为了弄清变慢的原因,我们做了几个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);

}

};

}

【div层的移动及性能优化】相关文章:

学习javascript文件加载优化

Angular发布1.5正式版,专注于向Angular 2的过渡

Javascript实现div层渐隐效果的方法

js跨域请求的5中解决方式

Javascript类型转换的规则实例解析

javascript实现十秒钟后注册按钮可点击的方法

JVM性能优化,Java的伸缩性

Javascript的IE和Firefox兼容性汇编

javascript鼠标滑动评分控件完整

javascript基础知识分享之类与函数化

精品推荐
分类导航