我的问题是,如何通过它的ID将图片从一个td元素移动到另一个元素?例如,当我有一个包含3行的表,每行有3个td元素时。我需要知道这一点,因为我想得到图片所在的td元素的id。之后,我想从那里删除图片并将其插入新的td元素。例如,从“数字 10 ”开始,使用函数movePicture(“left”),图片应向左移动1 td。选项应该是左,右,上,下或0,1,2,3。谢谢。
td{
width: 30px;
height: 30px;
background-color: lightblue;
text-align: center;
}
<table><tbody>
<tr>
<td id="number00">00</td>
<td id="number10">
<img src="pic.png" id="picture">10
</td>
<td id="number20">20</td>
</tr>
<tr>
<td id="number01">01</td>
<td id="number11">11</td>
<td id="number21">21</td>
</tr>
<tr>
<td id="number02">02</td>
<td id="number12">12</td>
<td id="number22">22</td>
</tr>
</tbody></table>
答案 0 :(得分:3)
图片具有唯一ID,因此无需查找包含图片的TD的ID。将图片从任何地方移动到第11位:
array=(7 5 3 1)
min()
{
local min=$1; shift
local n
for n in "$@"; do
if ((n<min)); then
min=$n
fi
done
echo "$min"
}
min "${array[@]}"
好了,现在听起来你需要一个功能:
document.getElementById('number11').appendChild(document.getElementById('picture'));
的示例:
function movePicture(direction) {
// get the id of the td that contains the picture
var currentTD = document.getElementById('picture').parentNode.id;
// extract the x and y values from the id
var x = Number(currentTD.charAt(6));
var y = Number(currentTD.charAt(7));
// alter the x or y value depending on what kind of move was requested
switch (direction) {
case "up":
if (y > 0) y--;
break;
case "down":
if (y < 2) y++;
break;
case "left":
if (x > 0) x--;
break;
case "right":
if (x < 2) x++;
break;
}
// move the picture to its new home
document.getElementById('number' + x + y).appendChild(document.getElementById('picture'));
}
快速setTimeout示例:
movePicture('down');
movePicture('left');
movePicture('up');
movePicture('right');