Uniapp 获取屏幕、元素的高度宽度

在遇到困难时先找官方文档方案,其实一些常用的方法官方都有对应的解决方案的。

获取系统信息:

    screenWidth 屏幕宽度 screenHeight 屏幕高度 windowWidth 可使用窗口宽度 windowHeight 可使用窗口高度 windowTop 可使用窗口的顶部位置 App、H5 windowBottom 可使用窗口的底部位置 App、H5 statusBarHeight 状态栏的高
uni.getSystemInfo({
    success: function (res) {
        console.log(res.model);
        console.log(res.pixelRatio);
        console.log(res.windowWidth);
        console.log(res.windowHeight);
        console.log(res.language);
        console.log(res.version);
        console.log(res.platform);
    }
});

示例

设置弹框宽度为屏幕的80%

<view class="set-plan-block" :style="{ width: setWidth + px }">

export default {
  data () {
    return {
      setWidth: 0
    }
  mounted () {
    this.$refs.setPlan.open()

    // 注意,这里要用个变量存this,不然进到getSystemInfo后this指向会变化,找不到data变量
    var _this = this
    uni.getSystemInfo({
      success: function (res) {
        _this.setWidth = res.windowWidth * 0.8
      }
    })
  },
注意:计算表达式不能用 80%(会报错),要用0.8 错:300 * 80% 对: 300 * 0.8

获取元素的宽度、高度、定位

可以获得如下信息:

    bottom: dataset,如ref proto: height: id left: right: top: width:
// uniapp的方法

uni.getSystemInfo({
  success: function (res) { // res - 各种参数

    let obj = uni.createSelectorQuery().select(.类名)

    obj.boundingClientRect(function (data) { // data - 各种参数
      
     console.log("datadata---",data)

    }).exec()
  }
})
经验分享 程序员 微信小程序 职场和发展