[Quick Application] Use of the general method getBoundingClientRect

【Key words】

Quick application development, general methods, getBoundingClientRect

[Background]
The getBoundingClientRect method is provided in the general method of the quick app to obtain the layout position of the current component. In the quick app problem dealt with before, a cp misunderstood this scene as the ability to get the width and height of the text, which is wrong. Reasonably, the current quick app does not provide a method to obtain the text height and width. So today we will learn how to use getBoundingClientRect in detail.

【introduce】

1. Call method: this.$element('xxx').getBoundingClientRect(Object object)

2. Parameter description:

cke_565.png

3. Instructions for callback success return value:

cke_1362.png

4. Precautions for calling getBoundingClientRect:

  • Components such as popup, option, span, picker do not support calling this method.
  • Since the component has not been created in the onInit method, calling this method in the onInit method will cause a js error.
  • Since the component has not been rendered in the onReady method, the result of calling this method in the onReady method is 0. Do not call this method before and during onReady.

【Result display】

The sample code is as follows:

<template>
  <!-- Only one root node is allowed in template. -->
  <div class="container">
    <text id="origin-text" class="origin-text">测</text>
  </div>
</template>

<style>
  .container {
    flex-direction: row;
    justify-content: center;
    margin-top: 30px;
  }
  .origin-text {
    width: 80px;
    font-size: 60px;
    height: 80px;
    font-weight: 500;
    border: 1px solid #000000;
  }
</style>

<script>
  module.exports = {
    data: {
      rect: {}
    },
    onInit() {
      this.$page.setTitleBar({
        text: 'getBoundingClientRect',
        textColor: '#ffffff',
        backgroundColor: '#007DFF',
        backgroundOpacity: 0.5,
        menu: true
      });
    },
    onShow() {
      var that = this;
      that.$element('origin-text').getBoundingClientRect({
        success: function (data) {
          that.rect = JSON.stringify(data);
          console.log(that.rect, 'rect');
        },
        fail() {
          console.log(`Failed to getBoundingClientRect`);
        }
      });
    },
  }
</script>

Display and print as follows:

cke_3761.png

cke_4645.png

As shown above, the width and height we get here are the width and height we set for this component, not the width and height of the text, and I will find that there will be precision errors in this value, which is normal.

Guess you like

Origin blog.csdn.net/Mayism123/article/details/131980174