【问题标题】:jquery hover and togglejquery悬停和切换
【发布时间】:2013-02-11 20:03:37
【问题描述】:

我有一些隐藏的文本,我想在单击按钮时显示它们。

按钮有四种不同的显示状态。当文本不显示时,它应该朝下,当文本显示时,它应该朝上。此外,还有向下和向上的悬停状态。

我还希望按钮在用户滚动 h1 标记时更改为悬停状态。它还应该根据是否显示文本显示正确的悬停状态。

我有一个fiddle link to demonstrate。

如果您删除下面的功能,它在点击时有效,但不适用于悬停状态:

    $('body.home .entry-content h1').hover(function() {
    $('#hide-text').css('background-position','-26px 0px');

}, function() {
    $('#hide-text').css('background-position','0px 0px');

});

【问题讨论】:

    标签: jquery hover toggle


    【解决方案1】:

    我稍微修改了您的代码以使用collapse 作为一个类,而不仅仅是hover。您需要这两个类,因为您希望有两种不同的状态(折叠和未折叠),每个状态都有自己的悬停。您的第一次尝试失败了,因为您将background-position 重置为悬停时的折叠位置,无论您想要什么状态。

    DEMO

    jQuery

    jQuery(document).ready(function ($) {
        $('body.home .entry-content h1').append("<div id='hide-text'></div>");
    
    
        $('body.home .entry-content h1').hover(function () {
            $('#hide-text').addClass("hover");
    
        }, function () {
            $('#hide-text').removeClass("hover");
        });
    
    
        $('#hide-text').toggle(function () {
            $(this).addClass('collapse');
            $('body.home .entry-content h2').fadeIn(500);
    
        }, function () {
    
            $(this).removeClass('collapse');
            $('body.home .entry-content h2').fadeOut(500);
    
        });
    
    });
    

    CSS

    body.home .entry-content h2 {
        display: none;
    }
    #hide-text {
        display: inline-block;
        position: relative;
        top: 2px;
        height: 22px;
        width: 26px;
        margin-left: 15px;
        background: url('http://www.mgrear.com/clients/gls/wp-content/themes/gravity-lab-studios/images/home-button.png') 0px 0px no-repeat;
    }
    #hide-text:hover, #hide-text.hover {
        background: url('http://www.mgrear.com/clients/gls/wp-content/themes/gravity-lab-studios/images/home-button.png') -26px 0px no-repeat;
        cursor: pointer;
    }
    #hide-text.collapse {
        background: url("http://www.mgrear.com/clients/gls/wp-content/themes/gravity-lab-studios/images/home-button.png") -52px 0px no-repeat;
    }
    #hide-text.collapse:hover, #hide-text.collapse.hover {
        background: url("http://www.mgrear.com/clients/gls/wp-content/themes/gravity-lab-studios/images/home-button.png") -78px 0px no-repeat;
    }
    

    【讨论】:

    • 非常感谢。这样可行!我现在明白我应该刚刚创建了两个类来处理这两个函数。这对我很有帮助。
    • 我是 stackoverflow 社区的新手。回答其他会员的问题对我有好处吗?
    • 如果您是一名认真的开发人员,拥有 SO 个人资料可能对您的职业生涯有好处。这是招聘人员和雇主验证您的技能的附加工具。这也是一种将孤独的编码员与那些可以帮助团队变得更好的编码员区分开来的方法。至于这个问题,如果我的回答解决了,就点我的回答旁边的复选框,‘接受’就好了。
    • SO 还可以提高您在各个领域的技能,因为您甚至在自己看到问题之前就已经回答了问题。每周花几个小时回答问题,相当于我书中的继续教育。
    • 感谢迈克尔的提示。通过帮助他人,您绝对可以学到更多。我现在正在回答问题。我想我刚刚发烧了!
    猜你喜欢
    • 2011-06-06
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多