当前位置: 移动技术网 > IT编程>网页制作>CSS > web在html中引用JavaScript代码的实现(小程序在xwml中实现)

web在html中引用JavaScript代码的实现(小程序在xwml中实现)

2019年04月30日  | 移动技术网IT编程  | 我要评论

step 1:新建wxs文件

date.wxs:处理信息时间的函数,将date格式的日期转化为如“刚刚”、“?分钟前”、“?天前“等时间文本。


var filter = {
  formatmsgtime: function (datestr) {
    var targetdate = getdate(datestr);
    var year = targetdate.getfullyear();
    var month = targetdate.getmonth() + 1;
    var day = targetdate.getdate();
    var hour = targetdate.gethours();
    var minute = targetdate.getminutes();
    var second = targetdate.getseconds();
    var nowdate = getdate();
    var now_new = date.parse(nowdate.todatestring());
    var milliseconds = 0;
    var timespanstr;

    milliseconds = now_new - targetdate;

    if (milliseconds <= 1000 * 60 * 1) {
      timespanstr = '刚刚';
    }
    else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
      timespanstr = math.round((milliseconds / (1000 * 60))) + '分钟前';
    }
    else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
      timespanstr = math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
    }
    else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
      timespanstr = math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
    }
    else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getfullyear()) {
      timespanstr = month + '-' + day;
    } else {
      timespanstr = year + '-' + month + '-' + day;
    }
    return timespanstr;
  }
}

module.exports = {
  formatmsgtime: filter.formatmsgtime
}

注:在wxs中无法new对象,这里要达到new date()的效果可采用全局函数getdate()。

step 2:引入wxml文件中


step 3:调用函数

    {{filter.formatmsgtime('2018-07-18 17:07:05')}}

其他示例:

var filter = {
  // float类型的value只保留两位小数
  numbertofix: function (value) {
    return value.tofixed(2);
  },
  // 判断数组array中是否存在值value
  valueinarray: function (array, value) {
    return array.indexof(value);
  }
}
module.exports = {
  numbertofix: filter.numbertofix,
  valueinarray: filter.valueinarray,
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网