javascript - 如何在 window.resize 之外获取实时值?

标签 javascript jquery

如何获取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);        

});

谢谢

最佳答案

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,因为您的变量范围没有在父函数中定义,因此您的所有内部函数都无法访问。

关于javascript - 如何在 window.resize 之外获取实时值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19972421/

相关文章:

javascript - ngInfiniteScroll 中的无限滚动立即检查有什么作用?

javascript - JQuery数据表插入数据后不刷新

javascript - JavaScript 中是否可以基于某些父属性名称进行 "dynamic"对象引用?

javascript - AngularJS 不重新加载部分 jQuery 脚本

javascript - 如何在选择框上方获取文本?

javascript - 如何通过ajax发送或获取日期值

jquery .remove() 方法不会触发 .on ('remove' ) 事件

JQuery Tablesorter memorizeSortOrder 小部件

javascript - RoR - .js 查看更多按钮(顶部)到查看更少按钮(底部)

javascript - 我很困惑。什么是 window.scrollY,它与 String.concat 之类的东西有什么不同?