【问题标题】:how to stop jquery change css of all the divs onhover of a single div如何停止jquery更改单个div的所有div的css onhover
【发布时间】:2013-04-20 19:52:00
【问题描述】:

我在 div 中显示了信息块。我想在悬停时更改特定 div 的 css。但是目前,当我将鼠标悬停在任何 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 受到影响。可能有很多学生,这意味着会产生很多“学生盒子”。

【问题讨论】:

    标签: javascript jquery css html onhover


    【解决方案1】:
    $('.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
       })
    );
    

    【讨论】:

    • 但是 student-box 和 student-info 是两个不同的类
    • 实际上$(this) 是一个包含被悬停的DOM 元素的jQuery 对象。 this 是 DOM 元素
    【解决方案2】:

    试试这个:

    $('.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() 方法,但最好添加一个类名并将样式移动到样式表中,否则您的行为会受到影响。

    【讨论】:

    • 我的样式表中确实有这些类,而且我还有其他属性。但是要创建悬停效果,我想我需要使用 jquery,rite?
    猜你喜欢
    • 2022-01-26
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多