你的位置:首页 > Java教程

[Java教程]js 宽窄屏切换效果优化感悟


源代码:

优化前: 

优化后代码:

 

 

<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 值是动态计算的, 使用该值时尽量先使用变量存储,避免再次计算。