2011-11-13 192 views
0

我正在閱讀教程,並繼續卡在第一行代碼,我知道PHP中的「新」是做一個對象,但本教程與此無關。請幫助什麼是簡單的JavaScript做什麼

var img = new Image(); 

教程是在這裏:

http://jqueryfordesigners.com/image-loading/

好吧,我找到了預定義的JavaScript對象圖像()的W3定義:http://www.w3schools.com/jsref/dom_obj_image.asp

+0

只是一個小紙條,這一行沒有任何關係jQuery的任何責任。 – BoltClock

+0

@BoltClock本教程是在jQuery中編寫的! '$(new Image())。attr(「src」,「image.png」)' – noob

+0

我說「這個特定的行」,而不是「教程」。 – BoltClock

回答

3

事實上,在JavaScript new是用於製作對象時,就像PHP一樣。

因此,您可以猜到,因此,該代碼行僅實例化Image對象並將其分配給img變量。

+0

好吧,這就是我thoight,但是,教程沒有定義「圖像」對象 –

+1

@A_funs:'圖像'是一個內置的DOM類,代表HTML圖像,所以它是可用的,默認情況下在大多數情況下,如果不所有瀏覽器。 – BoltClock

+0

如果你使用Firefox並且安裝了Firebug,你可以在頁面加載後輸入諸如console.log(img)或console.log(Image)之類的東西來檢查事情。這會告訴你,img是Image的一個實例化實例,而Image是一個函數。然後你就會知道Image是一個內置函數,因爲你沒有自己定義它。 – dnuttle

0

可以預加載

var img = new Image(); 
他們預裝圖像圖像

圖像/ headshot.jpg

然後他們等待,直到它已經加載

然後大公隱藏加載圖像和褪色在圖像

0

這與jQuery無關。

圖像是一個本地JavaScript對象,它對應於一個HTML圖像對象。

什麼行的意思,是 「創建一個新的變量‘IMG’,並將其設置到新初始化Image對象」

+0

但在教程中未定義圖像對象 –

+0

圖像對象已創建。它最初沒有任何與之相關的數據。請注意,本教程首先將「onload」事件附加到圖像對象,然後/然後/設置「src」屬性。 這具有創建對象,加載圖像,然後運行onload事件的效果。 如果你加載了src/before /設置onload,那麼緩存的圖像將永遠不會觸發他們的onload事件 –

+0

在本教程中使用了jQuery! – noob

0

這使HTML的形式爲您服務。

詳細閱讀本http://www.devguru.com/technologies/ecmascript/quickref/image.html

希望這可以幫助你很多。

,或者你想知道它是創造

var img = new Image(); 

,而不是使用?

$(img) 
    // once the image has loaded, execute this code 
    .load(function() { 
    // set the image hidden by default  
    $(this).hide(); 

    // with the holding div #loader, apply: 
    $('#loader') 

    // remove the loading class (so no background spinner), 
    .removeClass('loading') 
    // then insert our image 
    .append(this); 

    // fade our image in to create a nice effect 
    $(this).fadeIn(); 
    }) 

    // if there was an error loading the image, react accordingly 
    .error(function() { 
    // notify the user that the image could not be loaded 
    }) 

// *finally*, set the src attribute of the new image to our image 
.attr('src', 'images/headshot.jpg'); 
}); 

的「這個」關鍵字代表的img可變