A recently developed function, the picture is displayed in the parent box without being cropped and does not exceed the width and height of the parent box. If the width and height of the picture is smaller than the width and height of the parent box, it will be displayed at the original size. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>图片等比压缩适应父盒子宽高,并且不被裁切</title>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
.logo-wrap {
background-color: rgba(0, 0, 0, 0.5);
width: 375px;
height: 200px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
</style>
</head>
<body>
<div id="app">
<!-- 父盒子的宽高 375 200 -->
<div class="logo-wrap">
<img class="logo" ref="logo" :src="imgsArr[1]" alt="">
</div>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
imgsArr: [
'imgs/1.png',
'imgs/2.jpg',
'imgs/3.png',
'imgs/4.png',
'imgs/5.jpg',
],
// 经过等比压缩后的图片宽度
width: '',
// 经过等比压缩后的图片高度
height: '',
}
},
mounted() {
let that = this;
let width = '';
let height = '';
// 创建实例对象
var img = new Image();
// 图片地址
img.src = this.imgsArr[1];
// 为什么要写 onload 是因为要等他加载完之后才能获取到图片宽高,
// 直接通过this.$refs.logo.offsetWidth 获取图片的宽高是0
img.onload = function () {
// 返回的宽高是元素的实际大小
width = img.width;
height = img.height;
// 图片的宽高比
let ratio = width / height;
// 父盒子的宽高比
let bili = 375 / 200;
// 只有图片宽或者高大于父盒子对应的宽高才会执行,否则就展示原图的尺寸
if ((width >= 375 && height <= 200) || (width >= 375 && height >= 200) || width <= 375 && height >= 200) {
// 说明图片最大的尺寸是宽度
if (ratio > bili) {
height = Math.round(375 / width * height);
width = 375;
console.log('走1')
} else {
// 说明图片最大的尺寸是高度
width = Math.round(200 / height * width);
height = 200;
console.log('走2')
}
// 图片宽高相等的情况
} else if (width == height && height >= 200) {
width = height = 200;
console.log('走3')
};
that.width = width;
that.height = height;
console.log(width, height, '处理过后的图片宽高');
that.$refs.logo.style.width = that.width + 'px';
that.$refs.logo.style.height = that.height + 'px';
}
},
})
</script>
</body>
</html>
It should be noted that the width and height of this.$refs.logo.offsetWidth to obtain dynamic images are 0, and the img.onload method needs to be used.
Effect:
This is my summary.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。