2011-02-09 74 views
2

我最近在頁面底部的網站上實現了一個小框,當鼠標懸停在它上面時展開......這是代碼,它很好用。從懸停改爲點擊?

CSS

#box{ 
    position:absolute; 
    width:300px; 
    height:20px; 
    left: 33%; 
    right: 33%; 
    min-width: 32%; 
    bottom:0; 
    background-color: #353535; 
} 

的JavaScript

$('#box').hover(function() { 
    $(this).animate({ 
     height: '220px' 
    }, 150); 
},function() { 
    $(this).animate({ 
     height: '20px' 
    }, 500); 
}); 

但我很好奇,我怎麼會去改變這種打開和關閉的點擊,而不是鼠標懸停在它?

我是編輯,以...

$('#box').click(function() { 
    $(this).animate({ 
     height: '220px' 
    }, 150); 
},function() { 
    $(this).animate({ 
     height: '20px' 
    }, 500); 
}); 

而這個工程,以打開盒子。但我無法通過再次點擊再次關閉它。

太近了! :P

+0

?懸停功能有可能需要兩個參數,點擊功能只需要一個參數? – awm 2011-02-09 11:00:10

+0

我正在使用jQuery庫。 – Flickdraw 2011-02-09 11:51:09

+0

我看到你現在已經添加了jQuery標籤......很好! – awm 2011-02-10 07:25:24

回答

2

這應該是您使用的圖書館工作

$('#box').toggle(function() { 
    $(this).animate({ 
     height: '220px' 
    }, 150); 
},function() { 
    $(this).animate({ 
     height: '20px' 
    }, 500); 
}); 
1

你可以這樣做:

$('#box').click(function() { 
    if ($(this).is(':visible')) { 
    $(this).hide(); 
    return; 
    } 

    $(this).animate({height: '220px'}, 150); 
}); 

在單擊時,它會隱藏元素,如果別人看到它的動畫。

2

你或許可以只使用toggle event handler,而不是像這樣的單擊事件:

$('#box').toggle(function() {...}, function() {...});