SoFunction
Updated on 2025-04-06

How to get the width and height of the screen or box contents

Get the width and height of the screen, and you can use these values ​​for layout, style, or other operations as needed.

1. Obtain the screen width and height

Use the() method to obtain system information, including the width and height of the screen. (Note: The () method is an asynchronous method, so you need to process the obtained screen size data in the success callback function.)

methods: {
  getScreenSize() {
    ({
      success: (res) => {
        const screenWidth = ; // Screen width, unit is px        const screenHeight = ; // Screen height, unit is px        ('Screen Width:', screenWidth);
        ('Screen height:', screenHeight);
      },
    });
  },
},

Where you need to get the screen width and height, just call the getScreenSize() method.

mounted() {
  (); // Call the method to get screen size after the component or page is loaded},

Use and get the width and height of the screen:

const screenWidth = ; // Screen widthconst screenHeight = ; // Screen height

2. Obtain the width and height of the box content

Use the() method to create a selector query object to get the width and height of the box content. (Note: The () method is an asynchronous method, so you need to process the obtained box size data in the boundingClientRect callback function.)

methods: {
  getBoxSize() {
    ()
      .select('.box') // Select the box element you want to get the size, here assuming that the class of the box element is box      .boundingClientRect((rect) => {
        const boxWidth = ; // The width of the box is px        const boxHeight = ; // The height of the box is px        ('Box Width:', boxWidth);
        ('Box Height:', boxHeight);
      })
      .exec();
  },
},

Where you need to get the width and height of the box, just call the getBoxSize() method.

mounted() {
  (); // Call the method to get the box size after the component or page is loaded.},

In the Vue component, access the ref attribute through this.$refs and use $el to get the width and height of the box element:

<div ref="box" class="box"></div>

const boxWidth = this.$.$; // Box widthconst boxHeight = this.$.$; // Box height
(boxWidth,boxHeight);

Summarize

This is the article about how to obtain screen or box content width and height of Uniapp and Vue. For more related uniapp and Vue to obtain screen width and height of Uniapp and Vue, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!