1 Introduction
- Scenario: For example, APP cover, etc.
- Features: It can automatically adapt to the width and height of the device, ensuring 100% display of the picture without missing or leaving edges, but it may be deformed .
2. Realize
Note that although the following code is implemented in the Vue environment, it has little to do with Vue, and the code itself is simple enough that it can be extended to any other non-Vue JS environment with a little modification.
HTML:
<template>
<img src="picture.jpg" :width="width" :height="height">
</template>
Script:
<script>
export default {
data: () => ({
height:0,
width:0,
}),
methods: {
handleResize() {
// 获取屏幕宽高:
const screenWidth = window.innerWidth
const screenHeight = window.innerHeight
// 动态设置图片宽高:
this.height= screenHeight
this.width = screenWidth
},
},
mounted: function () {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
};
</script>