欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信小程序根据wx.getSystemInfo获取屏幕尺寸,并动态改变元素宽高尺寸,示例

程序员文章站 2022-05-23 23:46:55
...

通过js获取屏幕尺寸,并改变元素尺寸

效果图

微信小程序根据wx.getSystemInfo获取屏幕尺寸,并动态改变元素宽高尺寸,示例

index.wxml

<view class="body-view" style="width:{{wWidth}}rpx; height:{{wHeight}}rpx;">
  <view class="top-view" style="width:{{topWidth}}rpx; height:{{topHeight}}rpx;">
    <view class="welcome_title">欢迎使用XXX小程序</view>
  </view>
  <view class="middle-view" style="width:{{middleWidth}}rpx; height:{{middleHeight}}rpx;">
    <view class="welcome_text">正在开发,欢迎来访。。。</view>
  </view>
  <view class="bottom-view" style="width:{{bottomWidth}}rpx; height:{{bottomHeight}}rpx;">
    <button type="primary" class="shouquan_btn" bindtap="shouquan">授权使用</button>
  </view>
</view>

index.js

Page({
  data:{
    openid:"",
    wHeight:null,
    wWidth:null,
    topHeight:null,
    topWidth:null,
    middleHeight:null,
    middleWidth:null,
    bottomHeight:null,
    bottomWidth:null,
  },
  //页面显示事件
  onShow(){
    this.get_window_size();
  },
  //获取窗口尺寸
  get_window_size(){
    let that = this;
    // 获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        // 获取可使用窗口宽度
        let clientHeight = res.windowHeight;
        // 获取可使用窗口高度
        let clientWidth = res.windowWidth;
        // 算出比例
        let ratio = 750 / clientWidth;
        // 算出高度(单位rpx)
        let height = clientHeight * ratio;
        // 设置高度
        that.setData({wHeight: height});
        that.setData({wWidth: 750});

        that.setData({topHeight: height*0.15});
        that.setData({topWidth: 750});

        that.setData({middleHeight: height*0.7});
        that.setData({middleWidth: 750});

        that.setData({bottomHeight: height*0.15});
        that.setData({bottomWidth: 750});
      }
    });
  }
})

index.css

.body-view{ float: left; }
.top-view{float:left;}
.middle-view{ float:left; }
.bottom-view{ float: left; text-align: center; }

.top-view .welcome_title{ float:left; width:100vw; height: 15vw; text-align: center; font-size: 1.5rem;line-height: 15vw;}
.middle-view .welcome_text{ margin-left: 5vw; width:90vw; text-align: left; font-size: 1.0rem; line-height: 10vw;}
.bottom-view .shouquan_btn { margin:auto; }