2017-05-04 101 views
0

我的問題是,如何通過它的id將圖片從一個td元素移動到另一個元素?例如,當我有一個3行的表,每行有3個TD元素。我需要知道這一點,因爲我想獲得圖片所在的TD元素的ID。之後,我想從那裏刪除圖片並將其插入新的td元素。例如,從「編號」,使用movePicture函數(「左」),圖片應該向左移動1 td。選項應該是左,右,上,下或0,1,2,3。謝謝。 如何從表格中獲取圖片的ID並將其從一個td移動到另一個td?

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

你是否將圖片移動到了respons點擊一下?如何知道圖片應該移到哪裏? – James

+0

它是在例子中編寫的,從「number10」到「number11」...沒有一個點擊,例如一個函數movePicture(** 11 **);該函數應該通過它的id獲取圖片並從那裏刪除它...在這種情況下,它將是「number10」,然後它應該被移動到id爲「number ** 11 **」的td元素。 – bady

+0

因此,該功能只需要將圖片移動到同一列的正下方的行中? – Kramb

回答

3

畫面上有一個唯一的ID,以便找到包含圖片的TD的ID是沒有必要的。要在圖像移動從任何地方number11:

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')); 
} 

例子:

movePicture('down'); 
movePicture('left'); 
movePicture('up'); 
movePicture('right'); 

快速的setTimeout例如:

var moves = ['down','left','up','right']; // repeat when done 
var index = 0; 
function doTimedMove() { 
    if (index == moves.length) index = 0; 
    movePicture(moves[index]); 
    index++; 
    setTimeout(doTimedMove, 1000); 
} 
+0

我知道,但是例如,當我想讓圖片向右移動1 td時,我需要獲取td的「number10」的id,然後更改它的子字符串「number」+ colVar +「」 + rowVar。然後增加colVar。但爲此,我需要知道之前的號碼是什麼...... – bady

+0

這就是爲什麼我問你怎麼知道圖片的去向。目的地是基於當前圖片的位置嗎? – James

+0

好吧,我的錯,然後是的。我希望圖片能夠從當前位置1左移,右移,上移和下移。 – bady

相關問題