2010-11-23 40 views
0

我正在做一個關於定位圖像的練習,從一本書。它說,使用DOM,即圖像的位置,頂部和左側值,我們可以使用JavaScript在瀏覽器窗口中移動圖像。圖片在瀏覽器中沒有被移位

事情是我有圖像得到顯示,但是當我輸入座標時,它不會移位到它的新值。請如果有人能告訴我我要去哪裏錯?

這裏是HTML文件

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
    <head> 
    <title>Sample</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <script type="text/javascript" src="newjavascript.js"> 
    </script> 
    </head> 
    <body> 
     <form action=""> 
      <p> 
       Xcordinate : <input type="text" id="xCod" /><br/> 
       Ycordinate : <input type="text" id="yCOd" /><br/> 
      </p> 
      <br/> 
      <input type="submit" value="Set the Coordinates" onclick = "moveIt('image', document.getElementById('xCod').value, 
       document.getElementById('yCod').value)" /> 
     </form> 
     <div id="image" style="position: absolute; left:0; top:200px" > 
      <img src="testing.jpg" alt="Picture Cannot be displayed" /> 
     </div> 
    </body> 
</html> 

和JavaScript文件

function moveIt (movee, newTop, newLeft){ 
    dom = document.getElementById(movee).style; 

    dom.top=newTop+"px"; 
    dom.left=newLeft+"px"; 

} 

我有默認瀏覽器,谷歌瀏覽器

+0

看起來沒問題乍一看。按下「Ctrl + Shift + J」並點擊「控制檯」查看JavaScript錯誤 – 2010-11-23 23:48:19

回答

5

因爲它是一個type="submit"按鈕,它被張貼回來,你再次看到同一頁面,您需要return false;以防止提交,如下所示:

<input type="submit" value="Set the Coordinates" onclick = "moveIt('image', document.getElementById('xCod').value, 
      document.getElementById('yCod').value); return false;" /> 

設立演示你的元素ID是關閉還注意到,這樣的:

Ycordinate : <input type="text" id="yCOd" /><br/> 

應該是:

Ycordinate : <input type="text" id="yCod" /><br/> 

You can test it out (with both of the above fixes) here

+0

謝謝你:) – 2010-11-24 00:02:18

1

您有一個大寫問題(或您的文章中有錯字)。您的頁面中有一個元素,其ID爲yCOd,但您的代碼正在查找ID爲yCod

+0

謝謝你的幫助:) – 2010-11-24 00:02:40