2013-04-20 88 views
2

我有以div形式顯示的信息塊。我想更改懸停時特定div的CSS。但是,當我將鼠標懸停在任何div上時,所有div的css都會改變。如何阻止jquery更改一個div的所有div的css

這裏是我的jQuery代碼: -

<script> 
     $('.student-box').hover(function(){ 
      $('.student-info').css('opacity', '0.8'); 
      $('.student-info').css('margin-top', '-20px'); 
      $('.student-info').css('height', '130%'); 
      $('.onhover-ul').show(); 
     }, 
     function(){ 
      $('.student-info').css('opacity', '0.7'); 
      $('.student-info').css('margin-top', '75px'); 
      $('.student-info').css('height', '63%'); 
      $('.onhover-ul').hide(); 
     }); 
    </script> 

如何更改jQuery的,這樣僅是在徘徊在div受到影響。可以有很多學生,這意味着很多「學生箱」將會生成。

回答

1

試試這個:

$('.student-box').hover(function(){ 
    var div = $(this); 

    div.find('.student-info').css({ 
     opacity: '0.8' 
     marginTop: '-20px', 
     height: '130%' 
    }); 
    div.find('.onhover-ul').show(); 
}, function(){ 
    var div = $(this); 

    div.find('.student-info').css({ 
     opacity: '0.7', 
     marginTop: '75px', 
     height: '63%' 
    }); 
    div.find('.onhover-ul').hide(); 
}); 

不要緊,你叫hover()方法上的一個div,你仍然只是說「選擇與類的所有元素的回調裏面.. '

在回調函數中,this是實際觸發事件的DOM元素。所以你可以把它包裝在jQuery中並調用它的方法。

以這種方式使用css()方法雖然不建議,但您最好添加一個類名稱並將樣式移動到樣式表中,否則您的行爲會出現演示。

+0

謝謝,它的工作 – 2013-04-20 19:58:00

+0

我的樣式表中有這些類,而且我還有其他屬性。但是爲了創建懸停效果,我想我需要使用jquery,rite? – 2013-04-20 20:06:07

2
$('.student-box').hover(function(){  
     // $(this) is DOM element what hovered at this moment 

     $(this).find('.student-info').css({ 
      'opacity': '0.8', 
      'margin-top', '-20px', 
      'height', '130%' 
     }); 
    }, 
    function(){ 
     // unhover code like hover 
    }) 
); 
+0

但學生信箱和學生信息是兩個不同的類 – 2013-04-20 19:55:04

+0

是的,你可以找到需要元素,使用父元素 – Ozerich 2013-04-20 19:58:44

+0

Actualy'$(this)'是一個jQuery對象,包含被徘徊的DOM元素。 'this'是DOM元素 – danwellman 2013-04-20 20:01:27