2

I have blocks of information displayed in divs. I want to change the css of a particular div on hover. But currently when I hover over anyone div the css for all the divs change.

Here's my jquery code :-

<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> 

How do I change the jquery so that only the div which is hovered upon is affected. There can be a lot of student which means lot of "student-box" will be generated.

4

2 回答 2

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
   })
);
于 2013-04-20T19:53:56.067 回答
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();
});

您在 div 上调用该方法并不重要,hover()在回调中您仍然只是说“选择该类的所有元素......”

在回调函数内部,this是实际触发事件的 DOM 元素。因此,您可以将其包装在 jQuery 中并在其上调用方法。

虽然不建议以这种方式使用该css()方法,但最好添加一个类名并将样式移动到样式表中,否则您的行为中会有表现。

于 2013-04-20T19:55:39.083 回答