<!DOCTYPE html><html><head> <title></title> <mata http-equiv=”content-type” content=”text/html; charset=gb2312” /> <style type="text/css"> * { margin: 0; padding: 0; font-size: 14px; font-family: "微软雅黑"; } </style></head><body> <p id="p1" style="width:30px; height:30px;background:#808080; "></p> <p id="p2" style="width:30px; height:30px;background:#808080; margin-left:170px; "></p> <p id="p3" style="width:30px; height:30px;background:#808080; position:absolute;left:140px;top:200px;padding-left:0;"></p> <p id="p4" style="width:30px; height:30px;background:#808080; position:absolute;top:170px"></p></body></html><script type="text/javascript"> setInterval(change, 5); function change() { var p1 = document.getElementById('p1'); var p2 = document.getElementById('p2'); var p3 = document.getElementById('p3'); var p4 = document.getElementById('p4'); var x = parseInt(p1.style.width); console.log(x); if (x<200) { x++; } p1.style.width = x + "px"; if (x =="200") { var y = parseInt(p2.style.height); if (y<200) { y++; } p2.style.height = y + "px"; } if (y == "200") { var z = parseInt(p3.style.width); if (z < 200) { z++; } p3.style.width = z + "px"; } }</script>
解决方案
由于,HTML内坐标系是从左往右是X轴,从上到下是Y轴。你的第三条边,实际上是从红点开始延长的一个长方形:
由于,第三条边是从正方形p3
延长而来,而由于你增加了正方形的宽度,又因为屏幕从左向右为X轴正方向,所以宽度增加正方形会向右延长成长方形。而如果你要让这个变长的效果“看起来”是在向左移动,那么就要在每一次变长的同时,将红点向左移动相同的距离。
所以,对于p3
的操作应该这样写:
if (y == "200") { var z = parseInt(p3.style.width); if (z < 200) { z++; } p3.style.marginLeft = (-z + 30) + 'px'; // 加上上面一句,至于为什么是-z + 30 // 其实是-(z - 30) // 因为,原本方块的宽度就是30, // 那么,在X轴正方向(宽度增量就是z - 30) // 由于宽度向右伸长了z - 30 // 所以将左边距设置为-(z - 30),来抵消这个向右伸长的增量 // 所以,看起来就是在向左移动 // 实际上是伸长以后将整个图形同时向左移相应的距离 // 而并非是实际向左伸长 p3.style.width = z + "px";}
效果图: