画像をスタートボタンで動き始め、ストップボタンで、その場で止まるようにしたいです。画像が動くようにはなりましたが、領域内からはみ出てしまいます。ストップさせる方法もわかりません。
よろしくお願いします。
lang
1<!DOCTYPE html> 2<html> 3<head> 4<meta charset="UTF-8"> 5<title>第8週練習問題</title> 6<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 7</head> 8<body> 9<script> 10$(document).ready(function() { 11 var img = $('#img').attr('src', 12 'http://www.ics.ritsumei.ac.jp/wp-content/themes/ics/images/img_research01.gif').height(128).css({'left': 0, 'top': 0, 'position': 'absolute', cursor: 'pointer'}); 13 14 var div = $('#rect').css({border: 'dotted 1px', position: 'relative'}) 15 .width(480).height(360); 16 var width = div.width(); 17 var height = div.height(); 18 var x = 0, y = 0, divx = 1, divy = 1, velx = 4, vely = 4; 19 20 21 function loop(){ 22 23$('#img').css({left: x + 'px', top: y + 'px'}) 24 25 x = x + velx * divx; 26 if((x + ('#img').width > width) || (x < 0)){ 27 divx = - divx; 28 x = x + velx * divx; 29 } 30 y = y + vely * divy; 31 if((y + ('#img').height > height) || (y < 0)){ 32 divy = - divy; 33 y = y + vely * divy; 34 } 35 36 setTimeout(loop, 100); 37 } 38 39 40 $('#start-btn').on('click', function() { 41 42 loop(); 43 44 }); 45 $('#stop-btn').on('click', function() { 46 47 48 49 setTimeout(loop, 100); 50 51 }); 52}); 53 54 55</script> 56<div id="rect"> 57 <img id="img"> 58</div> 59<button id="start-btn">スタート</button> 60<button id="stop-btn">ストップ</button> 61</body> 62</html> 63 64
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/06/09 07:56
2015/06/09 07:59