2011-12-22 42 views
2

這不應該是一個問題,但我不明白爲什麼我的事件監聽器沒有觸發。我已經將我的代碼剝離到了靠近骨頭的地方,但仍然不會很好。添加一個事件監聽器到畫布

跳出來的唯一變量是我使用jQuery的jCanvas,但我懷疑這是什麼問題。

下面的代碼:

jQuery(document).ready(function(){ 

    // Get the Canvas set to the proper size 
canvas = document.getElementById("background"); 
    canvas.width = document.width; 
    canvas.height = document.height; 
    canvasW = canvas.width; 
    canvasH = canvas.height; 

canvas.addEventListener("mousedown", check,false); 
}); 


function check(ev) 
{ 
alert('click'); 
} 

感謝您抽出寶貴時間太長看我傻難題

回答

1

那麼,在the link you gave in the comment for the other answer,你顯然在背景畫布。如果元素位於另一個元素下,則事件不會觸發。您的畫布有z-index0,使其低於body。使用控制檯,我只是改變了z-index,它工作得很好。

在相關說明中,您可能已經看過Google的let it snow畫布。如果你注意到,一開始你不能和雪相互作用。它有一個低的z-index。過了一段時間,z-index增加了,你不能與文本交互;只有雪。如你所見,這與你使用畫布無關。只有當元素相互定位時事件纔會發揮作用。 Simple example illustrating my point.

+1

是的,我記得今天早上在洗澡時。我已經將導航欄移動到導航欄下方,以便我可以與兩者進行交互。謝謝你的努力! – PandemoniumSyndicate 2011-12-23 08:25:43

1

我覺得你的代碼工作。這就是我想http://jsfiddle.net/QXSsE/1/

jQuery(document).ready(function() { 

    // Get the Canvas set to the proper size 
    canvas = document.getElementById("background"); 

    var context = canvas.getContext('2d'); 
    if (context) { 
     // You are done! Now you can draw your first rectangle. 
     // You only need to provide the (x,y) coordinates, followed by the width and 
     // height dimensions. 
     context.fillRect(0, 0, 150, 100); 
    } 
    canvas.addEventListener("mousedown", check, false); 
}); 

function check(ev) { 
    alert('click'); 
} 
+0

@Alnitak對不起,這是一個錯字! – 2011-12-22 09:00:03