微信小程序常用的案例

微信小程序空格写法

在text标签后加上一个decode解码,里面输入跟html一样 其他一些符号同理。

所有的html转义的都可以,以下这个表是都有效果的

图片+文字

文字放置在图片的水平和垂直居中的位置上

wxml代码如下


<view class="image-parent">
  <image class='image' mode='widthFix' src='../../images/answer-ad.png'></image>
  <view class="child">child</view>
</view> 

wxss代码如下


.image {
   746rpx;
}
 
.image-parent {
  height: 746rpx; 
  position: relative;
  border: 2rpx solid red;
}
 
.child {
   100px;
  height: 24px;  
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  text-align: center;
  background: yellowgreen;
}  

  • 查看图片宽高比,上述示例中图片宽高比为1:1
  • wxml中标签设置mode为'widthFix',即“宽度不变,高度自动变化,保持原图宽高比不变”
  • 设置image宽度为w,上述示例中w=746rpx
  • 设置image所在的父容器height值,根据图片的宽高比,算出来image的height值,并且赋值给父容器height,上述示例中父容器height=746rpx(这一步必须注意,如果不设置父容器height与image的height值相等,会出现不居中或者图片底部会有一栏空白)
  • 注意文字的样式.child中通过绝对布局和margin实现了垂直居中

获取当前时间并展示在页面

1、在util.js (创建项目自动生成)中:

 // util.js
 const formatTime = date => {
   const year = date.getFullYear()
   const month = date.getMonth() + 1
   const day = date.getDate()
   const hour = date.getHours()
   const minute = date.getMinutes()
   const second = date.getSeconds()
  
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute].map(formatNumber).join(':')   //返回年月日,时分秒
}
 
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
 
module.exports = {
  formatTime: formatTime
}

2、index.wxml 中写一个text显示时间

<text class="user-motto">{{time}}</text> 

3、index.js中写逻辑

// index.js
  
 var util = require('../../utils/util.js');
 Page({
  ......................
   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function (options) {
    //日期显示
    var time = util.formatTime(new Date())
    //为页面中time赋值
    this.setData({
      time: time
    })
  },
 ............................
})

参考1参考2

人生有很多自己在意的事,但是要学会不介意!
原文地址:https://www.cnblogs.com/smqh-bokeyuan/p/15333514.html