1

如何在 window.resize 之后获取当前高度的值?

$(window).resize(function(){
    currHeight = $('#window-fixed').height();        
});

console.log( currHeight );
//Uncaught ReferenceError: currHeight is not defined

$('a.stp').click(function(e){
    e.preventDefault();

    var href = $(this).data('id');        

    $('html, body').animate({
        scrollTop: ( $(href).offset().top ) - currHeight
    }, 1200);        

});

谢谢

4

2 回答 2

2
var $winFix    = $('#window-fixed'),  // Cache your elements!
    currHeight = $winFix.height();    // Say hello to your variable!

$(window).resize(function(){
    currHeight = $winFix.height(); // modify your variable      
});

console.log( currHeight ); // nnn

$('a.stp').click(function(e){
    e.preventDefault();

    var href = $(this).data('id');        

    $('html, body').animate({
        scrollTop: ( $(href).offset().top ) - currHeight // Reuse it
    }, 1200);        

});

您遇到了ReferenceError,因为您的变量的范围未在父函数中定义,因此您的所有内部函数都无法访问。

于 2013-11-14T08:07:04.867 回答
0

声明currHeight为全局变量,如:

var currHeight = 0;

$(window).resize(function(){
    currHeight = $('#window-fixed').height();        
}).resize();    //  Calling resize() method on page load only

console.log( currHeight );  // You will get the `window-fixed` height here now
于 2013-11-14T08:08:46.700 回答