recalculate element height in jQuery after class change

只愿长相守 提交于 2019-12-07 02:17:38

问题


I've got a list of items and according to a criteria it gets a class via jQuery on document.ready that triggers CSS3 columns.

If the list is displayed in columns it would have a smaller height. Is there any way to get the new height in jQuery immediately after the class change?

$items.each(function(i){

var theItem = this;

console.log($(theItem).height());

//extended layout

if ( theCriteria ) {
    $(theItem).addClass('extended'); 
    console.log('after', $(theItem).height()); }
}

The code above returns the initial height on both calls. I'm guessing I need to trigger something else.


回答1:


A lot of times, dom manipulation doesn't occur until a function closure is complete.

A good article on the issue: http://www.quirksmode.org/blog/archives/2009/08/when_to_read_ou.html

It might be best to do a setTimeout function call instead of the direct log.

instead of:

console.log('after', $(theItem).height());

try

setTimeout(function(){ console.log('after', $(theItem).height()); }, 0);

Setting the timeout to 0 will make it run as soon as possible, while still after the current function that is running.

Hopefully that's your issue. Good luck.



来源:https://stackoverflow.com/questions/1997887/recalculate-element-height-in-jquery-after-class-change

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