2012-04-16 56 views
0

好吧,假設我在頁面上有多個鏈接,並且我希望鏈接在您翻閱時更改背景顏色。我會用這個代碼:在沒有ID的情況下更改特定實例

$(function() { 
    $('a').mouseover(function() { 
     $('a').css('background-color', 'black'); 
    }); 
}); 
$(function() { 
    $('a').mouseleave(function() { 
     $('a').css('background-color', 'white'); 
    }); 
}); 

與此代碼的問題是,當你翻轉之一,所有環節的變色。我可以給每一個特定的ID,併爲每個特定的功能,但有沒有更有效的方法來做到這一點? 編輯:此外,我能做些什麼來設置原始背景顏色回到原來的樣子。如果我將背景變成白色,首先它可能不是白色。我怎麼能解決這個問題?

+1

對於這個S pecific任務我會使用'a:hover {background-color:black; '用css。但是,也許你不只是在盤旋鏈接時詢問改變風格。 – 2012-04-16 22:28:30

+0

+1 to @LarsNyström。另外,你不需要/想要在'$(function(){...});'中包含每一行代碼。把它全部包裝在一起。 – 2012-04-16 22:34:23

回答

1

只是你知道,你們都這樣做了漫長而艱辛的方式。

// this is like document.onload = function, 
// this only needs to be called once, you can put 
// all your jQuery in this one function 
$(function() { 
    // the following is a call to all `a` links to add jQuery's own .hover function 
    // see -> http://api.jquery.com/hover/ 
    $("a").hover(function(eIn) { // this first function is the action taken when 
           // user hovers over the link 
     $(this).css({ 'background-color': '#000', 'color': '#fff' }); 
    }, function(eOut) { // this second function is what happens 
         // when user hover away from the link 
     $(this).css({ 'background-color': '', 'color': '' }); 
    }); 
}); 

​See WORKING Fiddle

此外,你不需要JQUERY對於這一點,使用CSS

在CSS:

a:hover { 
    background-color: #000; 
    color: #fff; 
}​ 

See it in CSS ONLY HERE

4

在您的版本中,您使用$('a')來調用.css()函數。問題是$('a')選擇頁面上的所有節點,而不僅僅是您移動鼠標的節點。在mouseover回調函數中,this關鍵字引用作爲事件發起者的節點。因此,當你在該函數中執行$(this)時,你將創建一個該節點的jQuery對象(稱爲包裝集)。現在你可以調用它的所有jquery函數,不包括.css()函數。所以在這裏,你去:

$(function() { 
    $('a').mouseover(function() { 
     $(this).css('background-color', 'black'); 
    }); 
}); 
$(function() { 
    $('a').mouseleave(function() { 
     $(this).css('background-color', 'white'); 
    }); 
}); 
+1

+1你打我吧 – 2012-04-16 22:26:44

+0

對不起。 :) – koenpeters 2012-04-16 22:27:24

+0

請解釋爲什麼這個工程。我知道它爲什麼會像許多其他人一樣,但對於OP來說可能並不明顯。 – Bojangles 2012-04-16 22:29:11

相關問題