2014-03-12 67 views
0

爲什麼我在slideDown動畫完成後無法獲取元素高度? 簡單的例子:jQuery在slideDown完成後獲取元素高度

var height; 
el.slideDown('slow', function() { 
    height = $(this).outerHeight(); 
}); 
console.log(height); 

相反,控制檯返回undefined值。這裏的生活在jsfiddle我希望能夠澄清一些,因爲我正在努力學習。謝謝! :)

回答

1

回調將在您的console.log調用後大約600毫秒後執行。當您調用log函數時,height變量仍然保存undefined值。

+0

哦確定..不知道在此之前,現在我知道該怎麼做,謝謝:)未定義 – covfefe

0

嘗試this小提琴

$('ul').on('click', '> li > a', function (e) { 
    var _this = $(this).parent(), 
     el = _this.children('p'), 
     opened = _this.siblings('.open'); 

    opened 
     .removeClass('open') 
     .slideUp('slow'); 

    if (el.is(':visible')) { 
     el.slideUp(300, 'easeInBack'); 
     _this.removeClass('open'); 
    } else { 
     var height; 
     el.slideDown('slow', function() { 
      height = _this.outerHeight(); 
     }).promise().done(function() { 
    alert(height)}); 

     _this.addClass('open'); 
    } 

    e.preventDefault(); 
});