2013-06-22 30 views
0

我有这个下面的动画:的Javascript振荡

<!DOCTYPE HTML> 
<html> 
<head> 
<style> 
.example_path { 
    position: relative; 
    overflow: hidden; 
    width: 530px; 
    height: 30px; 
    border: 3px solid #000; 
} 

.example_path .example_block { 
    position: absolute; 
    background-color: blue; 
    width: 30px; 
    height: 20px; 
    padding-top: 10px; 
    text-align: center; 
    color: #fff; 
    font-size: 10px; 
    white-space: nowrap; 
} 
</style> 
<script> 
function move(elem) { 

    var left = 0 

    function frame() { 

    left+=10 // update parameters 

    elem.style.left = left + 'mm' // show frame 

    if (left == 10000) // check finish condition 
     clearInterval(id) 
    } 

    var id = setInterval(frame, 1) // draw every 1ms 
} 
</script> 
</head> 

<body> 
<div onclick="move(this.children[0])" class="example_path"> 
    <div class="example_block"></div> 
</div> 
</body> 
</html> 

正如你看到的,蓝色块移动,如果它跨越它的矩形。我如何有蓝色块附近摆动的矩形边框来来回回保持速度恒定的整个...

(在我的情况下,速度为10米/秒又名以10mm/MS)

+0

请添加一些更多的细节,你需要从这段代码? –

+0

您是否复制了代码并将其粘贴到文本编辑器中,只需尝试一下并告诉我会发生什么情况?该块越过右边界的权利? @ZaheerAhmed – tenstar

+0

这是一个[JSFiddle](http://jsfiddle.net/d5y6w/)的问题。我建议为未来的问题添加一个 – SpenserJ

回答

2

您需要更新代码:Here is working JSfiddle

function move(elem) { 

     var left = 0 
     var fwdMove = true; 

     function frame() { 
      if (left < 0) { 
       fwdMove = true; 
      } else if (left > 520) { 
       fwdMove = false; 
      } 

      fwdMove?left += 10:left -= 10 
      elem.style.left = left + 'px' // show frame 
     }  
     var id = setInterval(frame, 1) // draw every 1ms 
    } 
+0

我会尝试,只需一秒 – tenstar

+0

是的,很棒,非常感谢,你当然应该接受!并加上一票! – tenstar

+0

可以请你以毫米为单位告诉我同样的事情,而不是在几秒钟内,我试着用mm代替px,但块停在某处 – tenstar

0

我们首先添加一个变量来跟踪我们正在走向的方向,我们不想改变你移动的速度有多快,所以我们用一个正或负1影响位置。

var direction = 1; // 1=Right, -1=Left 
var left = 0 

function frame() { 
    left+=(10 * direction); // update parameters 

由于mm是一个打印单元,我们正在浏览器中工作,我们将其更改为使用px。如果你真的需要使用mm,你必须找到一种方法在它们之间进行转换,以便盒子在适当的位置停下来。

elem.style.left = left + 'px' // show frame 

最后,我们检查我们是否已经超过了框的边界,如果是的话,我们把它放回框中并反转方向;

if (left <= 0) { 
    direction = 1; // Begin moving to the left 
    left = 0; // Put the box back in the path 
} else if (left >= (530 - 20)) { 
    direction = -1; // Begin moving to the right 
    left = (530 - 20); // Put the box back in the path 
} 

JSFiddle