SwiperCarousel.vue 2.7 KB
<template>
  <!-- 轮播容器,固定1920x300尺寸 -->
  <div
    v-if="adSwiperList && adSwiperList.frontAdVos.length > 0 && isShowAD"
    class="banner-container"
  >
    <el-carousel
      :height="`${height}px`"
      indicator-position="none"
      autoplay
      :interval="5000"
      arrow="never"
    >
      <!-- 遍历轮播数据 -->
      <el-carousel-item v-for="item in adSwiperList.frontAdVos" :key="item.id">
        <a :href="item.link" target="_blank" class="banner-link">
          <img
            :src="config.public.apiUrl + item.image"
            :alt="item.title"
            class="banner-image aspect-[4/1] max-[768px]:aspect-[2/1]"
            loading="lazy"
          />
        </a>
      </el-carousel-item>
    </el-carousel>

    <!-- 关闭广告按钮 -->
    <div class="close-button" @click="isShowAD = false">
      <span class="close-icon">x</span>
      <span class="close-text">关闭</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { adListType } from "~/api/types/ad";
defineProps<{
  adSwiperList: adListType | null;
}>();
// 定义轮播数据类型
interface BannerItem {
  title: string;
  link: string;
  image: string;
}

const isShowAD = ref(true);
const config = useRuntimeConfig();

// 响应式宽度
const windowWidth = ref(0);

// 监听窗口大小变化

onMounted(() => {
  windowWidth.value = window.innerWidth;
  window.addEventListener("resize", () => {
    windowWidth.value = window.innerWidth;
  });
});

onUnmounted(() => {
  window.removeEventListener("resize", () => {
    windowWidth.value = window.innerWidth;
  });
});

// 计算属性:高度 = 浏览器宽度 * 1/4
const height = computed(() => {
  if (windowWidth.value < 768) {
    return Math.floor((windowWidth.value * 1) / 2);
  } else {
    return Math.floor((windowWidth.value * 1) / 4);
  }
});
</script>

<style scoped lang="less">
/* 容器样式:适配1920宽度,居中显示 */
.banner-container {
  width: 100%;
  max-width: 1920px;
  margin: 0 auto;
  overflow: hidden;
  margin-bottom: 30px;
  position: relative;
}

/* 广告链接样式 */
.banner-link {
  display: block;
  width: 100%;
  height: 100%;
}

/* 图片样式:适配轮播容器,保持1920x300比例 */
.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保证图片不变形 */
}

.close-button {
  position: absolute;
  top: 4px;
  right: 4px;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding: 2px 12px;
  background-color: rgba(255, 255, 255, 0.35);
  border-radius: 10px;
  vertical-align: middle;
  .close-icon {
    font-size: 20px;
    margin-right: 2px;
    color: red;
    margin-top: -2px;
  }
}

@media screen and (max-width: 768px) {
  .banner-image {
    object-fit: contain;
  }
}
</style>