2013-06-22 82 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