如何计算每个元素的高度并将这些值用作函数中的变量? [英] How to calculate each element's height and use these values as a variable in function?
问题描述
我正在尝试创建一个简单的文本手风琴,该手风琴计算每个面板的高度并将此值作为变量返回.我可以使用诸如if ( i === 0 ) { $(this).height(); }
之类的if语句获取值,但无法将此变量传递到外部.我可以做到这一点没有使用变量,但是从长期来看,它变得毫无用处.
I am trying to create a simple text accordion which calculates each panel's height and return this value as a variable. I can get values with if statements like if ( i === 0 ) { $(this).height(); }
but can't get this variable to the outside.I can do this without using variable but it became useless in long term.
简而言之::我想计算每个元素的height
并在click
函数中使用此变量.
Brıefly: I want to calculate each element's height
and use this variable inside click
function.
Here is jsFiddle which includes the problem.
var panel = $('.holder div');
var trigger = $('a');
panel.each(function(i) {
//problem starts when i try to calculate each ele's height
var eachEleHeight = i.height();
trigger.click(function() {
$(this).prev('div').animate({'height':eachEleHeight+'px'},500);
//this works widthout var eachEleHeight but became useless
//$(this).prev('div').animate({'height':'300px'},500);
});
//this is for hiding text at doc.ready
panel.css('height','56px');
});
推荐答案
如果我很了解,请尝试以下方法:
If I well understood, try this :
panel.each(function(i, el) {
// create a reference to te current panel
var $el = $(el);
// execute a function immediately, passing both the panel and its height
(function(p, h) {
// the trigger is targeted as the next link after the current panel
p.next('a').click(function() {
p.animate({ height : h + 'px'},500);
});
}($el, $el.height()));
// set each panel height
$el.css('height','56px');
});
小提琴示例: http://jsfiddle.net/Aw39W/55/
这篇关于如何计算每个元素的高度并将这些值用作函数中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!