2014-05-25 275 views
0

我想創建一些東西,當點擊div元素內的圖像。它應該將其顏色更改爲藍色,並將背景顏色更改爲藍色。我寫的代碼是否正確?因爲它不能正常工作。另外,有沒有更好的方法來將CSS應用到元素上?jQuery的CSS屬性選擇

FIDDLE

var photo = $('#photo'); 
var html = $('html'); 
var bg = $('#bg'); 
$(photo).on('click', function(){ 
    $(this).hide() 
    .delay(600) 
    .fadeIn(300); 
    $(html, bg).css({ 
    background :'blue' 
    }); 
}); 

HTML

<div id='bg'> 
    <img id='photo' src="http://img.pixland.uz/u11878f337693s.jpg" alt="" /> 
</div> 
+0

的可能重複[如何運行兩個jQuery的動畫同時?](http://stackoverflow.com/questions/1251300/how-to-run-two-jquery-animations-simultaneously) – Vucko

+0

看到這個工作正常http://jsfiddle.net/Fagc9/1/ –

+0

@ ShekharPankaj不工作!!!! – Tukhsanov

回答

2

您正在使用照片作爲jQuery對象所以沒有必要再使用照片中的$,或嘗試像,

var photo = '#photo'; 
var html = 'html'; 
var bg = '#bg'; 
$(photo).on('click', function(){ 
    $(this).hide() 
    .delay(600) 
    .fadeIn(300); 
    $(html+','+ bg).css({ 
    // to make multiple selectors into a single one 
     background :'blue' 
    }); 
}); 

請參考multiple-selectors更多細節

Live Demo

+0

謝謝@Rohan Kumar這是我需要的人不理解我。 '謝謝' – Tukhsanov

+1

'$(html +','+ bg)'?我更喜歡'html.add(bg)'或'bg.add(html)' – Popnoodles

3

除了Rohan Kumar's answer,這當然是正確的全部,有用於組合jQuery的選擇的方法:$.fn.add。您可以將HTML元素,元素數組,jQuery選擇,jQuery選擇器或HTML字符串傳遞給它。在這種情況下,我們可以通過jQuery的對象之一創建:

在這種情況下,你可以做的選擇與html.add(bg)

var photo = $('#photo'); 
var html = $('html'); 
var bg = $('#bg'); 
photo.on('click', function(){ 
    $(this).hide() 
    .delay(600) 
    .fadeIn(300); 
    html.add(bg).css({ 
    background :'blue' 
    }); 
}); 

jsFiddle