微信小程序
基础事件
| 事件 | 说明 |
|---|---|
| catch:tap | 点击事件 |
| 微信小程序官方暂未提供 (所以只能自己动手,丰衣足食) | 双击事件 |
| catch:longpress | 手指长按事件 |
| catch:input | 键盘输入事件 |
| catch:confirm | 回车事件 |
| catch:focus | 输入框聚集事件 |
| catch:blur | 输入框失去焦点事件 |
| catch:change | value改变时触发 (输入框)事件 |
| catch:touchstart | 手指按下事件 |
| catch:touchmove | 手指移动事件 |
| catch:touchend | 手指抬起事件 |
| catch:touchcancel | 手指触摸动作被打断事件 |
| catch:submit | 提交表单事件 |
| catch:reset | 重置表单事件 |
band 和 catch 的区别?
bind:事件绑定不会阻止冒泡事件往上冒泡,简单来说,bind所绑定的事件对应会向上传递,让自己的父组件响应对应的事件。
catch:事件会把对应的事件阻拦在自己这里,只有自己能够响应对应事件。
因微信小程序并未提供双击事件,所以应当自己动手,丰衣足食
ts
/**
* 双击事件封装
* @param {*} hander 条件满足时执行的回调函数
* @param {*} howManyTimes 点击几次执行回调函数 (默认为2)
* @param {*} time 条件开始到结束的事件 (默认为300) (单位毫秒)
*/
double(hander, howManyTimes = 2, time = 300) {
// 判断该属性是否存在 ,如果_this.sum不存在,者指定默认值
let doubleSumTap = wx.getStorageSync("doubleSumTap");
doubleSumTap = doubleSumTap == "undefined" ? 0 : doubleSumTap;
// 当前索引增加
doubleSumTap++;
// 修改缓存的数据
wx.setStorageSync("doubleSumTap", doubleSumTap);
// 判断是否到达预设的时间
setTimeout(() => ((doubleSumTap = 0), wx.removeStorageSync("doubleSumTap")), time);
// 双击执行完成
if (doubleSumTap == howManyTimes) hander();
}选取图片
ts
export const collectPictures = function (sum) { // sum:表示选取图片的张数
let arr = [];
return new Promise((reslove, reject) => {
wx.chooseMedia({
count: sum,
mediaType: ['image'],
sourceType: ['album', 'camera'],
maxDuration: 30,
camera: 'back',
success(res) {
// _this.data.imgList.push(res.tempFiles[0].tempFilePath)
if (res.tempFiles.length == 1) {
arr.push(res.tempFiles[0].tempFilePath)
reslove(arr)
} else {
let i = 0
res.tempFiles.forEach(item => {
arr.push(item.tempFilePath)
i += 1;
if (res.tempFiles.length == i) {
reslove(arr)
}
})
}
},
fail(error) {
reject(error)
}
})
})
}图片预览
ts
// 图片预览
export const picturePreview = (target, all) => { // target 表示当前的图片地址 all表示当前imgs数据的所有值(array)
wx.previewImage({
current: target, // 当前显示图片的http链接
urls: imgList // 需要预览的图片http链接列表
});
}
//列: picturePreview(this.data.imgPath,[ this.data.imgPath ])
picturePreview(this.data.imgPath,[ this.data.imgPath ])文件预览
ts
// 预览文件
// tempFilePath要预览的文件路径,callback为回调函数,文件打开完成后要做什么事,callback(非必填)
previewFile(tempFilePath, callback) {
wx.downloadFile({
url: tempFilePath,
success: (res) => {
console.log(res)
wx.openDocument({
filePath: res.tempFilePath,
showMenu: true,
success(res) {
// 如果callback为真,则执行
callback && callback()
},
fail(err) {
console.log(err)
}
})
},
fail: (err) => {
console.log(err)
return this.showToast('下载失败', 'error')
},
complete: () => { }
});
},预览图片和视频
ts
previewMedio(tempFilePath, current = 0, showmenu = false) {
wx.downloadFile({
url: tempFilePath,
success(res) {
wx.previewMedia({
current: current,
sources: [res.tempFilePath],
showmenu: showmenu,
});
},
fail: (err) => {
console.log(err)
return this.showToast('下载失败', 'error')
},
})
},上传文件
ts
upfile(num, type = "all", extension) {
return new Promise(function (resolve, reject) {
wx.chooseMessageFile({
count: num,
type,
extension,
success(res) {
resolve(res)
},
fali(err) {
reject(err)
}
})
})
},上传图片或视频
ts
// 上传图片或视频
uploadMedia(num, type = "mix") {
return new Promise(function (resolve, reject) {
wx.chooseMedia({
count: num,
mediaType: type,
success(res) {
resolve(res)
},
fali(err) {
reject(err)
}
})
})
},防抖
ts
// 搜索防抖
export const SEARCH = (obj, callback) => {
clearTimeout(obj.timer)
obj.timer = setTimeout(() => callback && callback(), 1500);
}微信支付
ts
// 微信支付api
export const paymentMoney = (data) => {
return new Promise((reslove, reject) => {
wx.requestPayment({
/**
timeStamp: '', 时间戳
nonceStr: '', 随机字符串,长度为32个字符以下
package: '', 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=
paySign: '', 签名
signType: 'MD5', 签名算法,应与后台下单时的值一致
**/
...data,
success(response) {
reslove(response)
},
fail(error) {
reject(error)
}
})
})
}获取个人信息
ts
export const getInfo = () => {
return new Promise((reslove, reject) => {
wx.getUserProfile({
desc: '完善用户信息',
success(res) {
wx.login({
success(data) {
reslove({ iv: res.iv, code: data.code, encryptedData: res.encryptedData, info: res.userInfo })
},
fail(error) {
reject(error)
}
})
},
fail(error) {
reject(error)
}
})
})
}元素偏移距离
ts
deviation(id) {
return new Promise(response => {
wx.createSelectorQuery().select(id).boundingClientRect((rect) => {
rect.id // 节点的ID
rect.dataset // 节点的dataset
rect.left // 节点的左边界坐标
rect.right // 节点的右边界坐标
rect.top // 节点的上边界坐标
rect.bottom // 节点的下边界坐标
rect.width // 节点的宽度
rect.height // 节点的高度
}).exec(res => {
response({
minTop: parseInt(res[0].top), // 最小顶部距离
maxTop: parseInt(res[0].top) + parseInt(res[0].height), //盒子底部距离
minLeft: parseInt(res[0].left), // 最小左边距离
maxLeft: parseInt(res[0].left) + parseInt(res[0].width)
})
})
});
},
// 例如:
this.deviation('.minBox').then(data => console.log(data))提示信息
ts
/** 提示信息 **/
msgInfo(msg, icon = "none", timer = "2000") {
wx.showToast({
// 标题
title: msg,
// 图标
icon: icon,
// 显示时间
duration: timer
})
},
/** 警告框 **/
config(title) {
return new Promise((reslove, reject) => {
wx.showModal({
title: title,
// content: '这是一个模态弹窗',
success(res) {
if (res.confirm) {
reslove(true)
} else if (res.cancel) {
reject(false)
}
}
})
})
},
/** loading效果 **/
loading(title) {
wx.showLoading({
title,
})
},
// 取消提示框
hide() {
wx.hideLoading();
},保存图片到本地
ts
wx.saveImageToPhotosAlbum({
// 图片地址
filePath: this.imagePath,
});canvas自定义海报
ts
// 1. 导入painter组件
"painter":"/components/painter/painter"
// 2. 页面写入
<painter palette="{{paintPallette}}" bind:imgOK="onImgOK" bind:touchEnd="touchEnd" widthPixels="1000" />
<painter palette="{{paintPallette}}" bind:imgOK="onImgOK" widthPixels="1000" />
<image src="{{image}}" style="width: 654rpx; height: 1000rpx; margin-left:40rpx;"/>
3. js
// 导入绘制图像参数
import Card from '../../palette/card';
属性
data: {
imagePath: '',
},
方法
// 初始化,获取图片路径
onImgOK(e) {
this.setData({
imagePath: e.detail.path
});
},
// 保存
saveImage(){
let resolve = this.data;
if (resolve.imagePath && typeof resolve.imagePath === 'string') {
wx.saveImageToPhotosAlbum({
filePath: resolve.imagePath,
});
}
},
// 显示画板
open() {
this.setData({
paintPallette: new Card().palette(),
});
},
// 获取canvas图表路径的方法
/** 保存图片到临时的本地文件 **/
const ecComponent = this.selectComponent('#mychart-dom-graph');//获取echarts组件
ecComponent.canvasToTempFilePath({
//安卓机型此处不会成功回调
success: res => {
console.log(res.tempFilePath);
// paintPallette: new store.ShadowExample().palette(res.tempFilePath)
},
});
// 绘制海报参数
this.ShadowExample = class ShadowExample {
palette(path) {
return ({
width: '620rpx',
height: '1038rpx',
// background: '#eee',
views: [
// 背景一
{
type: 'image',
// url: 'https://res.facebodyfitness.com/onlinevideo/img/4a4a345e-e308-4d89-a829-739d5f06b50d.png',
url: 'https://res.facebodyfitness.com/onlinevideo/img/f91a1f7b-716e-4505-bb6b-9b00c635929d.',
css: {
width: '100%',
height: '100%',
},
},
// 背景二
{
type: 'image',
url: '/asset/gay.png',
css: {
width: '526rpx',
height: '796rpx',
"top": "64rpx",
"left": "47rpx"
},
},
//分数
{
type: 'image',
url: "/asset/icon/xingxing_green.png",
css: {
width: '184rpx',
height: '54rpx',
"top": "117rpx",
"left": "218rpx"
},
},
// 分数名
{
type: 'text',
text: `${_this.reportHeader.score}`,
css: {
left: '257rpx',
fontSize: '66rpx',
"color": "#FE8A36",
top: '104rpx',
"font- family": "DIN",
"font-weight": "bold",
},
},
// 分数名
{
type: 'text',
text: "分",
css: {
left: '340rpx',
fontSize: '30rpx',
"color": "#FE8A36",
top: '143rpx',
"font- family": "DIN",
"font-weight": "bold",
},
},
// 打败人数的比例
{
type: 'text',
text: "你已打败",
css: {
top: '195rpx',
left: '190rpx',
fontSize: '24rpx',
"color": "#EBEBEB",
"font- family": "PingFang SC",
// "font-weight": "bold",
},
},
// 打败人数的比例
{
type: 'text',
text: `${_this.exceed}%`,
css: {
width: "95rpx",
height: "30rpx",
textAlign: "center",
top: '195rpx',
left: '295rpx',
fontSize: '24rpx',
"color": "#7C30E0",
"font- family": "PingFang SC",
// "font-weight": "bold",
},
},
// 打败人数的比例
{
type: 'text',
text: "的人",
css: {
top: '195rpx',
left: '390rpx',
fontSize: '24rpx',
"color": "#EBEBEB",
"font- family": "PingFang SC",
// "font-weight": "bold",
},
},
// 体适能分数
{
type: 'text',
text: "体适能分数",
css: {
top: '243rpx',
left: '245rpx',
fontSize: '26rpx',
"color": "#EBEBEB",
"font- family": "PingFang SC",
// "font-weight": "bold",
},
},
// 雷达图
{
type: 'image',
url: path,
css: {
width: '433rpx',
height: '453rpx',
"top": "349rpx",
"left": "94rpx"
},
},
// 体适能分数
{
type: 'text',
text: `分享人:${wx.getStorageSync("info").name}`,
css: {
top: '901rpx',
left: '47rpx',
fontSize: '26rpx',
"color": "#EBEBEB",
"font- family": "PingFang SC",
},
},
// 体适能分数
{
type: 'text',
text: "我也要测,微信扫码",
css: {
top: '950rpx',
left: '47rpx',
fontSize: '26rpx',
"color": "#EBEBEB",
"font- family": "PingFang SC",
},
},
// 微信小程序
{
type: 'image',
url: '/asset/wx.jpg',
css: {
width: '118rpx',
height: '118rpx',
"top": "884rpx",
"left": "455rpx",
borderRadius: "20rpx",
},
},
],
});
}
}正则图片筛选(富文本图片样式修改)
正则筛选图片编辑
ts
formatRichText(html) {
return new Promise(res => {
let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
return match;
});
newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
return match;
});
newContent = newContent.replace(/<br[^>]*\/>/gi, '');
newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;border-radius: 10px;"');
res({ state: 200, html: newContent })
})
},正则筛选图片为数组
ts
// 筛选图片
var src = result.qualifications.match(/<img\s*src=\"([^\"]*?)\"[^>]*>/gi); // result.qualifications 为html的富文本
let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i // 匹配图片中的src
var urls = []
if (src) {
for (var i = 0; i < src.length; i++) {
urls = urls.concat(src[i].match(srcReg)[1])
}
}
console.log(urls); //urls: 存放图片路径的数据