Automatically calculate the width and height of the image and stretch it to full screen with simple implementation of CSS and VUE

insert image description here

1 Introduction

  1. Scenario: For example, APP cover, etc.
  2. 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>

Guess you like

Origin blog.csdn.net/rockage/article/details/131040065