设置图片固定尺寸后,可以通过 object-fit 属性调整图片展示的形式
object-fit: contain;
- 图片的长宽比不变,相应调整大小。
object-fit: cover;
- 当图片的长宽比与容器的长宽比不一致时,会被裁切。
object-fit: fill;
- 图片不再锁定长宽比,完全适应盒子容易得长宽,被拉抻填充满盒子。
object-fit: none;
- 以图片原尺寸居中展示到盒子中,不被拉伸压缩。多余部分被剪切。
DEMO 代码
<div class="validateForm">
<el-select v-model="imgObjectFit" placeholder="请选择属性" value-key="key">
<el-option
v-for="item in selectDict"
:key="item.key"
:label="item.label"
:value="item"
>
</el-option>
</el-select>
<p>属性 object-fit: {{ imgObjectFit.label }}</p>
<div class="imgContainer" :class="'imgContainer' + imgObjectFit.key">
<img :src="imgSrc" alt="" />
</div>
<p>原图</p>
<img :src="imgSrc" alt="" />
</div>
<script>
export default {
name: "dataEdit",
components: {},
data() {
return {
selectDict: [
{ label: "contain", key: 1 },
{ label: "cover", key: 2 },
{ label: "fill", key: 3 },
{ label: "none", key: 4 },
],
imgObjectFit: {},
imgSrc: require("../../../assets/image/testImg.png"),
};
},
mounted() {},
methods: {},
};
</script>
<style lang="less" scoped>
.validateForm {
width: 100%;
max-width: 800px;
height: 100%;
padding: 32px;
background: #fff;
.imgContainer {
width: 200px;
height: 200px;
background: #000;
border: 3px solid red;
&.imgContainer1 {
img {
object-fit: contain;
}
}
&.imgContainer2 {
img {
object-fit: cover;
}
}
&.imgContainer3 {
img {
object-fit: fill;
}
}
&.imgContainer4 {
img {
object-fit: none;
}
}
img {
width: 100%;
height: 100%;
}
}
}
</style>