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

多类场景下getElementsByClassName实现双Logo同步修改求助

解决同时替换两个Logo的问题

嘿,我来帮你搞定这个问题!你现在的代码只处理了第一个Header-branding-logo元素,没对Mobile-bar-branding-logo做操作,所以才没法同时替换两个Logo。这里有两种简单的调整方式,你可以选一个用:

方法一:分别处理两个Logo元素

这种方式直接针对两个类单独获取元素并替换,逻辑直观,适合确定每个类只有一个元素的场景:

window.onload = function() {
  // 获取桌面端Logo并替换地址
  const desktopLogo = document.getElementsByClassName('Header-branding-logo')[0];
  if (desktopLogo) {
    desktopLogo.src = 'https://static1.squarespace.com/static/5a9e8da0aa49a18379207907/t/5ac52f062b6a28a603df30cf/152...';
  }
  
  // 获取移动端Logo并替换地址
  const mobileLogo = document.getElementsByClassName('Mobile-bar-branding-logo')[0];
  if (mobileLogo) {
    mobileLogo.src = 'https://static1.squarespace.com/static/5a9e8da0aa49a18379207907/t/5ac52f062b6a28a603df30cf/152...';
  }
};

注:加了if判断是为了避免页面中某个元素不存在时触发报错,让代码更健壮。

如果以后可能新增同类型的Logo,或者想一次性处理多个元素,用querySelectorAll会更灵活:

window.onload = function() {
  // 一次性选中所有带有两个目标类的元素
  const logos = document.querySelectorAll('.Header-branding-logo, .Mobile-bar-branding-logo');
  
  // 遍历每个元素,统一设置新的Logo地址
  logos.forEach(logo => {
    logo.src = 'https://static1.squarespace.com/static/5a9e8da0aa49a18379207907/t/5ac52f062b6a28a603df30cf/152...';
  });
};

小优化建议

如果你的Logo地址是固定的,可以把它抽成一个变量,这样以后修改只需要改一处,不用重复粘贴地址:

window.onload = function() {
  const newLogoUrl = 'https://static1.squarespace.com/static/5a9e8da0aa49a18379207907/t/5ac52f062b6a28a603df30cf/152...';
  const logos = document.querySelectorAll('.Header-branding-logo, .Mobile-bar-branding-logo');
  
  logos.forEach(logo => {
    logo.src = newLogoUrl;
  });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:53:33