如何在jQuery点击事件内实现窗口Resize时更新变量值
解决汉堡菜单resize时定位失效的问题
我来帮你捋清楚问题出在哪,以及怎么修复~
问题根源
你目前的变量(nav、head_h这些)是定义在点击事件的回调函数内部的,只有当用户点击按钮时,才会计算一次这些变量的值。而你在resize函数里重置的变量,如果和点击回调里的变量不在同一个作用域,那点击时依然会使用旧的变量值,自然看不到效果。
修复方案
推荐把动态获取尺寸的逻辑抽成单独的函数,这样不管是点击事件还是resize事件,都能拿到最新的变量值,避免作用域问题。
方案1:抽离获取尺寸的函数(更推荐)
// 专门用来获取最新的菜单相关尺寸 function getNavDimensions() { return { navElement: jQuery("#nav_container"), headerHeight: jQuery('#fullhead_wrap').height(), navHeight: jQuery('#nav_container').height() // 补充你之前的nav_h逻辑 }; } // 点击按钮时,获取最新尺寸再操作 jQuery("#button").click(function(){ const dims = getNavDimensions(); // 这里用dims里的变量做定位,比如: dims.navElement.css('top', `${dims.headerHeight}px`); }); // 窗口 resize 时,不仅更新尺寸,还可以直接调整菜单位置 jQuery(window).resize(function(){ const dims = getNavDimensions(); dims.navElement.css('top', `${dims.headerHeight}px`); });
方案2:使用全局作用域变量
如果需要变量在多个地方复用,可以把变量声明在外部,然后用函数统一更新:
// 全局作用域声明变量 let navElement, headerHeight, navHeight; // 统一更新变量的函数 function updateNavVars() { navElement = jQuery("#nav_container"); headerHeight = jQuery('#fullhead_wrap').height(); navHeight = jQuery('#nav_container').height(); } // 页面加载时先初始化一次 updateNavVars(); // 点击事件直接用全局变量 jQuery("#button").click(function(){ navElement.css('top', `${headerHeight}px`); }); // resize时更新变量并调整位置 jQuery(window).resize(function(){ updateNavVars(); navElement.css('top', `${headerHeight}px`); });
额外优化提示
为了避免resize事件触发过于频繁导致性能问题,可以给resize事件加个防抖:
let resizeTimeout; jQuery(window).resize(function(){ clearTimeout(resizeTimeout); resizeTimeout = setTimeout(function(){ const dims = getNavDimensions(); dims.navElement.css('top', `${dims.headerHeight}px`); }, 200); // 200ms内只执行一次,可根据需求调整 });
内容的提问来源于stack exchange,提问作者Reece
相关产品推荐
相关产品推荐

