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

Astro.js+Preact项目移动端卡片图片偶发加载失败求助

问题描述

应用内的项目卡片在移动端环境下,部分项目图片偶尔出现加载失败的情况,必须刷新浏览器才能正常显示,桌面端浏览则完全正常。

技术栈

使用Astro.js搭配Preact开发。

问题演示视频

https://streamable.com/okquzk

相关代码

在Astro框架中,通过mdx或md数据创建集合时,传入图片路径无需添加public/前缀,直接写/projects/bhn.webp即可:

---
title: "Black Hat News"
heroImage: /projects/bhn.webp 
---

之后在Card.tsx组件中使用该图片:

import "./styles/card.css";

type Props = {
  title: string;
  heroImage: string;
  slug: string;
};

export const Card = ({ title, heroImage, slug }: Props) => (
  <a href={slug}>
    <div class="card">
      <img src={heroImage} alt={title} />
      <div class="info">
        <h1>{title}</h1>
      </div>
    </div>
  </a>
);

对应的CSS样式:

/* Set padding top to make a trick with aspect ratio 16:9 */
.card {
  padding: 1rem;
  width: 100%;
  padding-top: 56.25%;

  position: relative;
  display: flex;
  align-items: flex-end;
  transition: 0.4s ease-out;
  box-shadow: 0px 7px 10px rgba(0, 0, 0, 0.5);
  cursor: pointer;
}
.card:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  display: block;
  width: 100%;
  height: 100%;

  /* background: rgba(0, 0, 0, 0.6); */
  z-index: 2;
}

.card img {
  width: 100%;
  height: 100%;
  -o-object-fit: cover;
  object-fit: cover;
  object-position: center top;
  position: absolute;
  top: 0;
  left: 0;
}
.card .info {
  position: relative;
  z-index: 3;
  color: var(--color-text);
  background: var(--color-dark);
  padding: 0.4rem;
  border-radius: 5px;
}
.card .info h1 {
  font-size: var(--font-lg);
}

/* for desktop add nice effects */

@media (min-width: 1024px) {
  .card:hover {
    transform: translateY(10px);
  }
  .card:hover:before {
    opacity: 1;
    background: rgba(0, 0, 0, 0.6);
  }
  .card:hover .info {
    opacity: 1;
    transform: translateY(0px);
  }
  .card:before {
    transition: 0.3s;
    opacity: 0;
  }

  .card .info {
    opacity: 0;
    transform: translateY(30px);
    transition: 0.3s;
  }
  .card .info h1 {
    margin: 0px;
  }
}
补充内容

新增组件使用代码:

import "./styles/projectsGrid.css";
import { useStore } from "@nanostores/preact";
import { getProjectsByTag } from "@utils/*";
import type { CollectionEntry } from "astro:content";
import { tagValue } from "src/tagStore";
import { Card } from "./Card";

type Props = {
  projects: CollectionEntry<"projects">[];
};

export const ProjectsGrid = ({ projects }: Props) => {
  const $tagValue = useStore(tagValue);

  const filteredProjects = getProjectsByTag(projects, $tagValue);

  return (
    <div class="projects_wrapper">
      {filteredProjects.map(({ data: { title, heroImage }, slug }) => (
        <Card title={title} heroImage={heroImage} slug={slug} />
      ))}
    </div>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:10:35