2012-01-30 64 views
2

我想要一個具有固定的小高度的元素,可以在鼠標懸停時擴展到其全高,並在鼠標離開時收縮。jquery:mouseover加載狀態

做這樣的事情:

$(".element").each(function() { 
    $.data(this, 'size', { width: $(this).width(), height: $(this).height() }); 
}).hover(function() { 
    $(this).stop().animate({ height: $.data(this,'size').height, 
          width: $.data(this,'size').width }); 
}, function() { 
    $(this).stop().animate({ height: 40, 
          width: $.data(this,'size').width }); 
}); 

...作品,但頁面上加載的元素開始在全高度。

在頁面加載時縮小頁面的最佳方法是什麼?

+0

有趣的問題。在加載頁面之前是否有機會知道渲染的高度/寬度?或者有什麼機會可以在頁面加載後縮小它們?我不積極如何解決這個問題。 – mrtsherman 2012-01-30 04:18:01

+0

我不知道元素的高度。事實上,我有很多這樣的人,他們都是不同的身高,這取決於他們所包含的內容。我不知道如何在頁面加載後使它們縮小。 – St0rM 2012-01-30 04:21:21

+0

@ Ken:確實。 – St0rM 2012-01-30 04:36:32

回答

2

試試這樣,最好能理解。檢查小提琴的例子。通過這種方式,你甚至可以添加像改變背景顏色等動畫效果.....

CSS:

.div_small_height{ 
height : 20px; 
width : 500px; 
background-color : red; 
overflow : hidden; 
} 
.div_full_height{ 
    width : 500px; 
    background-color : blue; 
} 

的Jquery:

$(".element").addClass('div_small_height'); // shrink it on page load 
// change on mouseenter and mouse leave 
$(".element").hover(function(){ 
    $(this).switchClass("div_small_height","div_full_height",500); 
},function(){ 
    $(this).switchClass("div_full_height","div_small_height",500); 
}); 

小提琴例如:http://jsfiddle.net/7PV98/

+0

對於其他人來說,'switchClass'是jQuery UI庫的一部分。您需要添加它才能使此代碼正常工作。 – mrtsherman 2012-01-30 04:38:15

+0

不知道.switchClass()會爲轉換添加動畫。偉大的解決方案,謝謝:-) – St0rM 2012-01-30 04:38:33

+0

不客氣的人... :) – 2012-01-30 04:40:45

0

你可以縮小頁面加載後通過調用你的hoverout c當文件準備就緒時。你可能想要使它們動起來,以使它看起來很好,以防它們被渲染。或者你可能想直接設置高度。

$(document).ready(function() { 
    $('element').each(function() { 
     //store height and width 
     $.data(this, 'size', { width: $(this).width(), height: $(this).height() }); 
     //shrink it 
     $(this).animate({ height: 40, width: $.data(this,'size').width }); 
    }); 
}); 

我很好奇,看看有沒有辦法做到這一點,但沒有動畫加載後,雖然。

0

你已經說過每個元素的高度並不是事先知道的。因此,您的一個問題是如何在加載時捕獲每個元素的自然高度,但仍然找到一種方法,僅在縮小到固定摺疊大小後才顯示該元素(避免每個元素都以其全尺寸顯示) 。

一種可能的策略是將對象呈現爲其自然大小,但在視口之外 - 例如,水平移動了-1000像素。捕獲並存儲它們的尺寸,然後將它們縮小到固定的40像素高度,然後將它們重新放回其常規視口位置。如果所有對象都位於某種容器元素中,則可以簡單地移動該元素。