2013-04-20 90 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