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

如何用JavaScript将图片的Alt文本自动插入H1标签中?

自动将图片Alt文本填入对应H1标签

我帮你修改代码,实现自动把图片的alt文本填充到对应卡片的空H1标签里,下面是完整的实现方案:

核心思路

  1. 遍历所有翻转卡片
  2. 从每张卡片背面的图片里提取alt文本
  3. 把alt文本填入同一张卡片正面的空H1标签
  4. 确保页面加载完成后再执行操作,避免找不到元素的问题

修改后的完整代码

JavaScript

function altToH1() {
  // 获取页面上所有的翻转卡片
  const flipCards = document.querySelectorAll('.flip-card');
  
  // 逐个处理每张卡片
  flipCards.forEach(card => {
    // 获取当前卡片背面图片的alt文本
    const imgAltText = card.querySelector('.flip-card-back img').alt;
    // 把alt文本填入当前卡片正面的H1标签
    card.querySelector('.flip-card-front h1').textContent = imgAltText;
  });
}

// 页面所有元素加载完成后执行函数
window.addEventListener('DOMContentLoaded', altToH1);

CSS

.flip-card {
  background-color: transparent;
  width: 200px;
  height: 300px;
  perspective: 1000px;
  display: inline-block;
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.6s;
  transform-style: preserve-3d;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}

.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg);
}

.flip-card-front, .flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.flip-card-front {
  background-color: #5bccf6;
  color: white;
  font-weight: 900;
  /* 让H1在卡片里垂直水平居中 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.flip-card-back {
  background-color: #5bccf6;
  color: white;
  transform: rotateY(180deg);
}

HTML

<div class="Obsada">
<div class="flip-card">
  <div class="flip-card-inner">
    <div class="flip-card-front">
      <h1></h1>
    </div>
    <div class="flip-card-back">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Heart_coraz%C3%B3n.svg/800px-Heart_coraz%C3%B3n.svg.png" alt="test test" style="width:200px;height:300px;">
    </div>
  </div>
</div>
<!-- 可以添加更多相同结构的flip-card,函数会自动处理每一张 -->
</div>

简单说明

  • 不管你有多少张翻转卡片,这个函数都会自动处理每一张的alt文本填充
  • DOMContentLoaded事件确保页面完全加载后再执行代码,不会出现找不到元素的错误
  • 我给CSS加了一行样式,让H1文本在卡片里居中显示,看起来更美观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 08:37:14