我试图获得一个具有可变高度的框列表,以便能够在一个函数上使用.animate()隐藏/显示内容。我试图用.height()获取内容框的高度,但是我也需要将框高度设置为从0px开始,这样页面就会加载,框会关闭以便开始。
问题出现在我对变量不好的时候。我可以让事情发挥作用,但是一旦我将所有框设置为从0px(全局)开始...我设置的变量单击以查找内容大小找到我为初始状态设置的0px的大小...所以盒子可以关闭,但没有高度重新打开。
如果你在JSFIDDLE注释掉第一行,如下所示,你可以看到它有点工作:
//$(".className").find("p").not(".trigger").css({height: '0px'});
BTW:我知道我用$(this).parent()。bla()。bla()。bla();不是选择这些项目最有效的方法,但我的网站实际代码更复杂,我想保持它类似。 THX!的
答案 0 :(得分:1)
这是一种方法:
/** Set up an object. **/
var allElementHeightsOriginally = {
heights: {}
};
var triggerElementHeight = $(".trigger").height();
/** Add the original heights to the object, along with the element indices. **/
$(".className").each(function (index, element) {
allElementHeightsOriginally.heights[index] = {
index: index,
original: ($(element).height()-triggerElementHeight)
};
});
/** Your click event. **/
$(".trigger").click(function () {
var indexClicked = $(".trigger").index(this);
var theElement = $(this).parent().find("p").not(".trigger");
$.each(allElementHeightsOriginally.heights, function (theKey, valueArray){
if(indexClicked == theKey){
var height = valueArray.original;
$selected = $(theElement);
if ($(theElement).hasClass('toggle')) {
$selected.stop().animate({height:"0px"});
$(theElement).removeClass('toggle');
} else {
$selected.stop().animate({height: height + 'px' });
$(theElement).addClass('toggle');
}
}
});
});
/** Collapse by default. **/
$("p").not(".trigger").css({height: '0px'});
我不确定上面的代码是否遵循最佳实践,但它确实有效!