I have an image in the cell of a table and I want it to move from one cell to another at random. I was planning on using the setInterval and Math.random() to move the image around randomly every two seconds but I cannot get the image to move around at all
<html>
<head>
<style>
tr { width: 300px; height: 100px }
td { width: 100px; height: 100px }
img { width: 100px; height: 100px }
</style>
<script>
function moveImgRandomly()
{
}
</script>
</head>
<body bgcolor="lightblue">
<table border=1 id="myTable">
<tr>
<td></td>
<td></td>
<td><img src="http://graemehobbs93.files.wordpress.com/2012/01/ape-1.jpg" id="img"></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
This is what I have so far that works. I have been trying for hours to get the image to move and it will not. I also cannot use jQuery.
This should do it.
var img = document.getElementById("img"); var tds = document.getElementsByTagName("td"); setInterval(function(){ var randomNumber = Math.floor(Math.random() * tds.length); tds[randomNumber].appendChild(img); }, 2000);
tr { width: 300px; height: 100px } td { width: 100px; height: 100px } img { width: 100px; height: 100px }
<body bgcolor="lightblue"> <table border=1 id="myTable"> <tr> <td></td> <td></td> <td><img src="http://graemehobbs93.files.wordpress.com/2012/01/ape-1.jpg" id="img"></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </table> </body>
function clearAll(){ var elements = document.getElementsByTagName('td'); for (var i=0;i<elements.length;i++){ elements[i].innerHTML="<p></p>"; } } setInterval(function(){ clearAll(); var elements = document.getElementsByTagName('td'); var ind = Math.floor(Math.random() * elements.length); elements[ind].innerHTML ='<img src="http://www.online-image-editor.com/help/images/photo_border.png" >'; }, 3000);
tr { height: 100px}; td { width: 100px; height: 100px; display:block; }; img { width: 100px; height: 100px; } td p { padding:100px; }
<table border=1 id="myTable"> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.