SwiperCarousel.vue
2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<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>