码迷,mamicode.com
首页 > Web开发 > 详细

js 宽窄屏切换效果优化感悟

时间:2016-02-29 09:17:50      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

源代码:

优化前: 

优化后代码:

 

 

<script type="text/javascript">

var oCr = document.getElementById("contentRight");

var oWide = document.getElementById("wide");

var oNarrow = document.getElementById("narrow");

var timer1;

var timer2;

var p = oCr.offsetWidth;

function closeCR() {

if (p > 0) {

p -= 5;

oCr.style.width = p + "px"

} else {

clearInterval(timer1);

}

}

function openCR() {

if (p > 195) {

clearInterval(timer2);

} else {

p += 5;

oCr.style.width = p + "px"

}

}

oWide.onclick = function () {

if (p > 0) {

clearInterval(timer2);

}

timer1 = setInterval("closeCR()", 10);

oNarrow.style.display = "block";

}

oNarrow.onclick = function () {

clearInterval(timer1);

timer2 = setInterval("openCR()", 10);

oNarrow.style.display = "none";

}

</script>

<script type="text/javascript">

//宽窄屏切换

var oCr = document.getElementById("contentRight");

var oWide = document.getElementById("wide");

var oNarrow = document.getElementById("narrow");

var timer1;

var p = oCr.offsetWidth, viewWidth = p;

function changeCR( ratio) {

p = p + ratio*4;

oCr.style.width = p + "px";

if(p > viewWidth || p<0) {

clearInterval(timer1);

}

}

oWide.onclick = function () {

timer1 = setInterval("changeCR(-1)", 10);

oNarrow.style.display = "block";

};

oNarrow.onclick = function () {

timer1 = setInterval("changeCR(1)", 10);

oNarrow.style.display = "none";

}

</script>

 

 

1.可使用坐标系分析判断条件的节点以及判断的值域。当无法确定判断的值域时,检查判断是否必要

   

2.不直接使用 offsetWidth 作为判断的条件。元素的 offsetWidth 值是动态计算的, 使用该值时尽量先使用变量存储,避免再次计算。

js 宽窄屏切换效果优化感悟

标签:

原文地址:http://www.cnblogs.com/plumeofstar/p/5226298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!