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

修改Popup Gallery,默认显示首张图片

实现页面加载默认显示首张图片弹窗

要实现打开网站就默认显示首张图片的完整大图,只需要在现有代码基础上做一处简单修改:

修改方案

在JavaScript代码末尾添加页面初始化逻辑,自动加载首张图片并激活弹窗:

// 页面加载完成后自动初始化首张图片弹窗
window.addEventListener('DOMContentLoaded', () => {
  updateImage(0);
  popup.classList.add('active');
});

修改后的完整JavaScript代码

const images = [...document.querySelectorAll('.image')];
const popup = document.querySelector('.popup');
const closeBtn = document.querySelector('.close-btn');
const imageName = document.querySelector('.image-name');
const largeImage = document.querySelector('.large-image');
const imageIndex = document.querySelector('.index');
const leftArrow = document.querySelector('.left-arrow');
const rightArrow = document.querySelector('.right-arrow');

let index = 0;

images.forEach((item, i) => {
  item.addEventListener('click', () => {
    updateImage(i);
    popup.classList.toggle('active');
  })
})

const updateImage = (i) => {
  let path = `img/img${i+1}.png`;
  largeImage.src = path;
  imageName.innerHTML = path;
  imageIndex.innerHTML = `0${i+1}`;
  index = i;
}

closeBtn.addEventListener('click', () => {
  popup.classList.toggle('active');
})

leftArrow.addEventListener('click', () => {
  if (index > 0) {
    updateImage(index - 1);
  }
})

rightArrow.addEventListener('click', () => {
  if (index < images.length - 1) {
    updateImage(index + 1);
  }
})

// 新增:页面加载自动激活弹窗并加载首张图片
window.addEventListener('DOMContentLoaded', () => {
  updateImage(0);
  popup.classList.add('active');
});

逻辑说明

  • DOMContentLoaded事件确保页面所有DOM元素加载完成后再执行初始化,避免出现找不到元素的错误
  • updateImage(0)将弹窗内的图片路径、名称、索引同步为首张图片的数据
  • popup.classList.add('active')触发CSS中定义的弹窗显示动画,让弹窗从隐藏状态切换为可见

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:22:02