You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify页面Google My Map切换标签页后地图不居中问题求助

问题:Shopify标签页中Google My Map无法居中显示

第一个标签页的Google My Map显示正常,但切换到第二个标签页时,地图无法居中。

原因

Google Maps嵌入的iframe在隐藏容器中初始化时,无法正确获取容器的实际尺寸,导致地图加载后布局错位,无法居中显示。初始状态下第二个标签页是隐藏的,iframe加载时容器尺寸计算错误,引发了这个问题。

解决方案

修改标签页切换的JS逻辑,在切换到目标标签页后,重新触发iframe的加载(或强制刷新地图容器尺寸),让Google Maps能正确识别当前容器的尺寸。

修改后的JS代码

$(document).ready(function() {
  $('ul.tabs').each(function(){
    var active, content, links = $(this).find('a');
    active = links.first().addClass('active');
    content = $(active.attr('href'));

    // 初始隐藏非第一个标签页,暂存iframe的src并移除
    links.not(':first').each(function () {
      var tabContent = $($(this).attr('href'));
      tabContent.hide();
      tabContent.find('iframe').each(function(){
        $(this).data('src', $(this).attr('src')).removeAttr('src');
      });
    });

    // 加载第一个标签页的地图
    content.find('iframe').each(function(){
      $(this).attr('src', $(this).data('src') || $(this).attr('src'));
    });

    $(this).find('a').click(function(e){
      e.preventDefault();
      active.removeClass('active');
      content.hide();

      active = $(this);
      content = $($(this).attr('href'));

      active.addClass('active');
      content.show();

      // 激活标签页后加载/刷新地图
      content.find('iframe').each(function(){
        if(!$(this).attr('src')){
          $(this).attr('src', $(this).data('src'));
        } else {
          // 刷新iframe让地图重新计算尺寸
          var src = $(this).attr('src');
          $(this).attr('src', '').attr('src', src);
        }
      });
    });
  });
});

补充说明

  • 初始时将非活跃标签页的iframe的src暂存到data-src属性,移除src避免提前加载,确保只有标签页被激活时才加载地图。
  • 对于已加载过的地图,切换回标签页时刷新iframe,强制Google Maps重新计算容器尺寸,保证地图居中显示。

验证效果

修改代码后,切换到第二个标签页时,地图会在容器显示后再加载(或刷新),此时能正确获取容器尺寸,地图即可正常居中。

内容的提问来源于stack exchange,提问作者EMMS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:45:24