2011-06-07 56 views
1

我想获得几个div来响应我的mouseOver和mouseOut。我正在尝试构建类似于Vimeo风格的音量栏。JQuery:将div返回初始高度

我得到了对mouseOver作出反应的条形图,但我希望它们在mouseOut后返回到原始高度。每个酒吧是不同的高度。它在硬编码时起作用,但我试图尽可能少地使用代码。

这里是我的JQuery:

$(document).ready(function() { 
var totalHeight = '100%'; 
var initHeight; 

function getHeight(h) { 
    initHeight = h; 
    //alert(initHeight); 
} 

$("div#barWrap").children().mouseover(function() { 
    // This is where I am having trouble. I want to get the original height of the bar so I can reuse it on mouseOut 
    getHeight($("div#barWrap").children().css('height')); 
    // Animate bar 
    $(this).animate({ height: totalHeight}, 100); 
}); 

$("div#barWrap").children().mouseout(function() { 
    $(this).animate({ height: initHeight}, 400); 
}); 

});

任何帮助将不胜感激。

回答

4

存储初始高度为每个元素的数据:

var totalHeight = '100%', 
    $bwc = $('div#barWrap').children(); 

$bwc.each(function(i,el) { 
    $(this).data('height', $(this).height()); 
}); 

$bwc.mouseover(function() { 
    $(this).animate({ height: totalHeight}, 100); 
}); 

$bwc.mouseout(function() { 
    $(this).animate({ height: $(this).data('height') }, 400); 
}); 
+0

这个固定的问题!非常感谢! – joolz84 2011-06-08 00:47:28

0

另一种解决方案是,如果使用CSS过渡你能够瞄准现代浏览器。

0

height:auto的一个div换成overflow:hiddenheight:0,然后点击后,检查内部div的高度,并将其设置为outer。尝试一下!

HTML:

<div id="visible-by-year" class="filter-visible"> 
    <div id="content"><br><br><br><br><br><br><br><br><br></div> 
</div> 

CSS:

.filter-visible{ 
background: gray; 
height: 0; 
#content{ 
    height: auto; 
    position: relative; 
} 

}

JS

$('.by-year').on('click', function() { 
    //$('.visible-by-year').toggleClass('show-by-year') 
    // 
    // $('#visible-by-year').animate({ height: $("#visible-by-year").data('height') }, 400); 
    var contentHeight = $('#content').height(); 
    $('#visible-by-year').animate({ height: contentHeight}, 500); 

    console.log(contentHeight); 


});