2013-02-11 88 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