2013-02-11 85 views
0

我有一些隐藏的文本,我想单击按钮时显示。jquery悬停和切换

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

我还想让按钮在用户滚过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'); 

}); 

回答

0

我修改你的代码位使用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; 
} 
+0

非常感谢。这样可行!我现在明白我应该创建两个类来处理这两个函数。这真的帮助了我。 – MGDTech 2013-02-11 20:49:33

+0

我是新来的stackoverflow社区。回答其他成员的问题对我有益吗? – MGDTech 2013-02-11 20:51:19

+0

如果您是一位认真的开发人员,拥有SO配置文件可能对您的职业生涯有益。这是招聘人员和雇主验证你的技能的额外工具。这也是将独立编码者与那些可以帮助团队变得更好的编程者分开的一种方式。至于这个问题,如果通过我的回答解决了问题,只需点击我答案旁边的复选框并点击“接受”即可。 – 2013-02-11 21:18:26