2015-05-09 83 views
0

我正在使用Jquery進行點擊事件。當我改變css屬性時,它很簡單,但我想要改變(畫布)HTML中的大小的一個元素。如何創建一個改變html屬性的點擊功能?

我試圖訪問和更改在點擊這個網站碼 - 寬度和高度:

<canvas id="testCanvas" width="755" height="500" > </canvas> 

與這個jQuery

$('#flipthehood').click(function(){ 
    console.log('hood flipped clicked'); 
    $getElementById('testCanvas').animate({width="200"}, 250); 
}) 

這是去了解它的最佳方式?如果是這樣,我可以請一些建議的語法,使其工作?我得到的意外錯誤=簽署

非常感謝

+0

'{width =「200」}'不是有效的JS對象,你想'{width:「200」}' – jdphenix

+0

另外,'$ getElementById('testCanvas')''必須是'$('#testCanvas ')' –

+0

使用'.css({})'方法。 –

回答

1

使用jQuery的ID選擇提取元素,

document.getElementById('testCanvas')相當於$('#testCanvas')

.animate()正確的語法是這樣的:

$('#testCanvas').animate({width:"200"}, 250); 
+0

謝謝你的伴侶 –

-1

要使用jQuery更改元素屬性,請使用.attr()方法d:

$("#testCanvas).attr("width", 200)

1

確保當文檔準備好你的點擊事件。另外document.getElementById不在JQuery中使用。這工作:

$(document).ready(function() { 
    $('#flipthehood').click(function(){ 
     console.log('hood flipped clicked'); 
     $('#testCanvas').attr("width", "200"); 
    }); 
}); 

如果你希望它是一個平滑的動畫簡單地將它改成這樣:

$(document).ready(function() { 
    $('#flipthehood').click(function(){ 
     console.log('hood flipped clicked'); 
     $('#testCanvas').animate({width: "200"}, 250); 
    }); 
}); 

$ .animate使用冒號,而不是等號。