微信小程序根據wx.getSystemInfo獲取屏幕尺寸,並動態改變元素寬高尺寸,示例

通過js獲取屏幕尺寸,並改變元素尺寸

效果圖

在這裏插入圖片描述

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; }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章