2012-07-17 84 views
2

我只是試圖用Javascript庫Raphael創建一些簡單的矢量圖形。應該有一個方形物體和一個彎曲的物體,但沒有顯示任何東西。誰能幫我。謝謝。圖形不顯示

<html> 

<head> 
<script src="raphael.js"></script> 
<script src="jquery-1.7.2.js"></script> 

<script type="text/javascript"> //all your javascript goes here 
var paper = Raphael("sample-2", 200, 100); 
var rectPath = paper.path("M10,10L10,90L90,90L90,10Z"); 
var curvePath = paper.path("M110,10s55,25 40,80Z"); 

rectPath.attr({fill:"green"}); 
curvePath.attr({fill:"blue"}); 
</script> 

</head> 

<body> 

<div id="sample-2" style="width:500px; height:500px;"> 

</div> 

</body> 

</html> 
+0

我怎麼能告訴? – 2012-07-17 19:44:55

+0

問題解決了!感謝所有幫助過的人。 – 2012-07-17 19:49:01

回答

2

你正在運行你的Javascript太早。您的瀏覽器在讀取它時會運行Javascript,如果DOM元素尚未加載,則不會執行任何操作。

試試這個:

<html> 
    <head> 
     <script src="raphael.js"></script> 
     <script src="jquery-1.7.2.js"></script> 
    </head> 

    <body> 
     <div id="sample-2" style="width:500px; height:500px;"></div> 
     <script type="text/javascript"> 
      //all your javascript goes here 
      var paper = Raphael("sample-2", 200, 100); 
      var rectPath = paper.path("M10,10L10,90L90,90L90,10Z"); 
      var curvePath = paper.path("M110,10s55,25 40,80Z"); 

      rectPath.attr({ 
       fill: "green" 
      }); 
      curvePath.attr({ 
       fill: "blue" 
      }); 
     </script> 
    </body> 
</html> 

享受和好運氣!

3

移動你的腳本來<div id="sample-2" style="width:500px; height:500px;">標籤後

或者有些人喜歡使用onload處理,使用jQuery爲了簡單

$(function(){ 
    // Your code that runs after the DOM is loaded 
}); 

的關鍵是,你的代碼訪問DOM並且需要在DOM構建完成後運行。從onload處理程序調用它或在您使用的DIV之後確保該元素已準備好與之交互。

+0

工作!如何爲新手+1 +1 – 2012-07-17 19:46:00

+0

你能告訴我爲什麼我必須這樣做才能工作嗎? – 2012-07-17 19:46:20

+0

他意味着,當您將onload處理程序等待頁面加載,然後將新的指令應用於DOM之前,必須在DOM之前繪製並插入DOM的圖像,然後再與DOM進行交互。把它放在DIV後面,確保你的代碼在DIV創建後執行,我會推薦使用onload。顯然,所有這些都應該被包含在'$(document).ready(function(){// code})中' – 2012-07-17 19:59:47

1

@JuanMendes它有點混亂,最後問題是js函數在DOM準備好之前被調用,元素仍然被創建。我建議使用$(document).ready(function(){}),以便只有在創建DOM後才執行腳本。我只是再次解釋,因爲他問他爲什麼要這樣做。例如,如果他這樣做:

<html> 

<head> 
<script src="raphael.js"></script> 
<script src="jquery-1.7.2.js"></script> 

<script type="text/javascript"> 
$(document).ready(function(){ //all your javascript goes here 
var paper = Raphael("sample-2", 200, 100); 
var rectPath = paper.path("M10,10L10,90L90,90L90,10Z"); 
var curvePath = paper.path("M110,10s55,25 40,80Z"); 

rectPath.attr({fill:"green"}); 
curvePath.attr({fill:"blue"}); 
} 
) 
</script> 

</head> 

<body> 

<div id="sample-2" style="width:500px; height:500px;"> 

</div> 

</body> 

</html> 

該腳本應該工作,因爲該腳本在DOM準備就緒後執行。

P.S.在附註中,如果要操縱動態創建的內容,則需要將事件處理程序作爲單擊,模糊,懸停等附加到綁定操作,以便註冊事件。例如:

$('#form').on('blur', '#input', function(){ 
// code 

}) 

你可以檢查出的文檔在綁定: http://api.jquery.com/on/ 和在。就緒(): http://api.jquery.com/ready/

+0

我不需要解釋,不需要需要標記我。我只是說你的解釋不清楚。 – 2012-07-17 22:05:24

+0

對不起,只是想澄清事情 – 2012-07-17 22:09:47