How to calculate each element's height and use these values as a variable in function?

拥有回忆 提交于 2019-12-13 21:04:15

问题


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.

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');
});​

回答1:


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');
});

Example fiddle : http://jsfiddle.net/Aw39W/55/




回答2:


There is a problem with the code you posted. i is the index of the current element. Not the element itself.

Try var eachEleHeight = $(this).height();

Fiddle




回答3:


The sequence of events you've used seems a bit weird. You're actually binding a click event to all a tags for each panel element. Try this: Fiddle

I just used the min-height and max-height css attributes to store the initial to/from height variables. This will automatically get you your starting heights.




回答4:


If I understand the question, you want to have the elements height for the accordion animation function. This is a trick but it works. I frequently use Mootools so I'll write using it. You should be able to figure it out.

var orgHeight = i.offsetHeight;
i.setStyle('height','100%');
var eachEleHeight = i.offsetHeight;
i.setStyle('height',orgHeight);

Essentially you would be flipping the element to reveal it's height and flipping it back before the document has time to make it visible on screen.

Not sure this is exactly what you were looking for, but hope it helps.



来源:https://stackoverflow.com/questions/12372821/how-to-calculate-each-elements-height-and-use-these-values-as-a-variable-in-fun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!