2017-03-23 23 views
0

我有一個簡單的遊戲,我有一個動畫圖像在屏幕上飛行,你點擊得分點。大約5秒後,圖像將飛離屏幕。我只是想通過任何必要的手段將它包含在div中。jquery設置一個邊界,所以動畫不會離開屏幕

$(document).ready(function() { 
$('#cursor').animate({ 
    top: '500px' 
    , left: '500px' 
}); 
$('img').click(function() { 
    var randomNumber = Math.random(); 
    console.log(randomNumber); 
     $('#output').html(function (i, val) { 
      return val * 1 + 10 
     }); 
    $(this).animate({ 
     top: '+=' + ((Math.random() * 500) - 400) + 'px' 
     , left: '+=' + ((Math.random() * 500) - 400) + 'px' 
    }) 
}) 

function explode() { 
    alert("TIME UP!"); 
} 
setTimeout(explode, 10000); 

});

這個解決方案只是一個CSS修復或需要在jQuery中完成嗎?

回答

0

1. 不要在動畫中使用「+ =」。

$(this).animate({ 
    top: '+=' + ((Math.random() * 500) - 400) + 'px' 
    , left: '+=' + ((Math.random() * 500) - 400) + 'px' 
}) 

2. 爲了遏制其在視口中考慮使用 window.innerHeightwindow.innerWidth

3. 爲了遏制它在一個div你需要知道的div寬度和heigth並將其考慮進你的計算中(例如,將最大值/高度乘以0到1之間的隨機數並從中減去圖像大小)

將圖像包含到視口

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Title</title> 
    <script 
      src="https://code.jquery.com/jquery-2.2.4.js" 
      integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" 
      crossorigin="anonymous"></script> 
</head> 
<body> 

<img style="background: black; width: 15px; height: 15px; position: relative"></img> 
<script> 
    $(document).ready(function() { 
     $('img').click(function() { 
      $(this).animate({ 
       top: (Math.random() * window.innerHeight - this.height) + 'px' 
       , left: (Math.random() * window.innerWidth - this.width) + 'px' 
      }) 
     }) 
    }) 
</script> 
</body> 
</html> 

你可以很容易地適應這個包含你的圖像在你的div。

+0

非常感謝你,要試一試。 –