2012-11-10 66 views
0

希望任何人都可以提供幫助。atr onmouseover toRaphaël.jsvars在for循環中創建

我從svg文件中獲取了大量的路徑(這裏只顯示了一些),我將它們存儲在一個數組中,以在Raphael紙上動態創建它們。

var paths = "M539.99,181v95.141h-0.12L509.521,181H539.99zdivideM539.99,276.511v84.85h-30.41L539.99,276.511zdivideM539.99,85.021V181h-30.47L539.99,85.021"; // string with paths from svg file. Much much bigger in real code 
var pathsArray = paths.split("divide"); // putting all paths in an array 

一切正常,直到我嘗試將屬性分配給for循環中的onmouseover函數中的路徑。什麼都沒發生。並且在控制檯中沒有錯誤消息。

var currentPath = window['section' + i]; 
currentPath.node.onmouseover = function() { 
    this.style.cursor = 'pointer'; 
    currentPath.attr("fill", "#ccc"); // <-- THIS PART DOESNT WORK 
} 

我也嘗試這種方式:

window['section' + i].attr("fill", "#ccc"); 

這使我的錯誤消息: 類型錯誤: '未定義' 不是一個對象(計算 '窗口[' 部分」 + i]中。 ATTR')

下面是完整的代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<script type="text/javascript" src="jquery-1.8.2.js"></script> 
<script type="text/javascript" src="raphael.js"></script> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<title>Untitled Document</title> 
</head> 

<body> 

<script type="text/javascript"> 

var paths = "M539.99,181v95.141h-0.12L509.521,181H539.99zdivideM539.99,276.511v84.85h-30.41L539.99,276.511zdivideM539.99,85.021V181h-30.47L539.99,85.021"; // string with paths from svg file. Much much bigger in real code 
var pathsArray = paths.split("divide"); // putting all paths in an array 

var paper = Raphael(10, 50, 1000, 1000); 

for (var i=0;i<pathsArray.length;i++) 
{ 

var currentPath = window['section' + i]; 

currentPath = paper.path(pathsArray[i]); 
currentPath.attr("fill", "#f00"); 
currentPath.attr("stroke", "#fff"); 
currentPath.node.onmouseover = function() { 
    this.style.cursor = 'pointer'; 
    currentPath.attr("fill", "#ccc"); // <-- THIS PART DOESNT WORK 
} 

} 

</script> 

</body> 
</html> 

回答

0

嘗試使用關鍵字,也根據documentation有一個內置的鼠標懸停事件。所以下面也應該工作:

currentPath.mouseover(function() { 
    this.node.style.cursor = 'pointer'; // using 'node' property to get access to DOM element 
    this.attr("fill", "#ccc"); // 'this' should refer to Raphael element 
}); 

即使currentPath是處理函數裏面,它總是在走循環的最後「currentPath」的值。

+1

這太好了,迷失了!我愛你,非常感謝! :) –