有些情况我们需要在各种刁钻的情况下都要保持图片比例不变,比如用户缩放窗口等改变布局的情况。实现原理就是通过容器的宽度和内边距在保持你想要的比例。

以下是基础功能的组件示例:

<template>
    <div style="position: relative" :style="ratioStr">
        <div style="position: absolute; inset: 0px; user-select: none">
            <img
                v-if="type === 'image'"
                :src="src"
                :alt="alt || src"
                style="object-fit: cover; width: 100%; height: 100%" />
            <video
                v-else
                :src="src"
                controls
                style="object-fit: contain; width: 100%; height: 100%" />
        </div>
    </div>
</template>

<script lang="ts" setup>
const props = defineProps({
    ratio: {
        type: Array as unknown as () => [number, number],
        default: () => [1, 1],
    },
    alt: {
        type: String,
        default: "",
    },
    type: {
        type: String as () => "image" | "video",
        default: "image",
    },
    src: {
        type: String,
        default: "",
    },
});

const ratioStr = computed(() => {
    const [width, paddingBottom] = props.ratio;
    return `width: 100%;padding-bottom: ${(paddingBottom / width) * 100}%;`;
});
</script>

<style lang="scss" scoped></style>

关于我们

本文由ChatMoney团队出品,ChatMoney专注于AI应用落地与变现,我们提供全套、持续更新的AI源码系统与可执行的变现方案,致力于帮助更多人利用AI来变现,欢迎进入ChatMoney获取更多AI变现方案!

06-07 15:58