如何在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);
});
由于
答案 0 :(得分: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 ,导致您的变量范围未在父函数中定义,因此无法访问所有内部函数。
答案 1 :(得分: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