ylbtech-小程序-demo:小程序示例-page/api |
以下将演示小程序接口能力,具体属性参数详见小程序开发文档。
1. page/component返回顶部 |
1、
a) .js
Page({
data: {
list: [
{
id: 'api',
name: '开放接口',
open: false,
pages: [
{
zh: '微信登录',
url: 'login/login'
}, {
zh: '获取用户信息',
url: 'get-user-info/get-user-info'
}, {
zh: '发起支付',
url: 'request-payment/request-payment'
}, {
zh: '分享',
url: 'share/share'
}, {
zh: '客服消息',
url: 'custom-message/custom-message'
}, {
zh: '模板消息',
url: 'template-message/template-message'
}
]
}, {
id: 'page',
name: '界面',
open: false,
pages: [
{
zh: '设置界面标题',
url: 'set-navigation-bar-title/set-navigation-bar-title'
}, {
zh: '标题栏加载动画',
url: 'navigation-bar-loading/navigation-bar-loading'
}, {
zh: '页面跳转',
url: 'navigator/navigator'
}, {
zh: '下拉刷新',
url: 'pull-down-refresh/pull-down-refresh'
}, {
zh: '创建动画',
url: 'animation/animation'
}, {
zh: '创建绘画',
url: 'canvas/canvas'
}, {
zh: '显示操作菜单',
url: 'action-sheet/action-sheet'
}, {
zh: '显示模态弹窗',
url: 'modal/modal'
}, {
zh: '显示消息提示框',
url: 'toast/toast'
}
]
}, {
id: 'device',
name: '设备',
open: false,
pages: [
{
zh: '获取手机网络状态',
url: 'get-network-type/get-network-type'
}, {
zh: '获取手机系统信息',
url: 'get-system-info/get-system-info'
}, {
zh: '监听重力感应数据',
url: 'on-accelerometer-change/on-accelerometer-change'
}, {
zh: '监听罗盘数据',
url: 'on-compass-change/on-compass-change'
}, {
zh: '打电话',
url: 'make-phone-call/make-phone-call'
}, {
zh: '扫码',
url: 'scan-code/scan-code'
}
]
}, {
id: 'network',
name: '网络',
open: false,
pages: [
{
zh: '发起一个请求',
url: 'request/request'
}, {
zh: 'WebSocket',
url: 'web-socket/web-socket'
}, {
zh: '上传文件',
url: 'upload-file/upload-file'
}, {
zh: '下载文件',
url: 'download-file/download-file'
}
]
}, {
id: 'media',
name: '媒体',
open: false,
pages: [
{
zh: '图片',
url: 'image/image'
}, {
zh: '录音',
url: 'voice/voice'
}, {
zh: '背景音频',
url: 'background-audio/background-audio'
}, {
zh: '文件',
url: 'file/file'
}, {
zh: '视频',
url: 'video/video'
}
]
}, {
id: 'location',
name: '位置',
open: false,
pages: [
{
zh: '获取当前位置',
url: 'get-location/get-location'
}, {
zh: '使用原生地图查看位置',
url: 'open-location/open-location'
}, {
zh: '使用原生地图选择位置',
url: 'choose-location/choose-location'
}
]
}, {
id: 'storage',
name: '数据',
url: 'storage/storage'
}
]
},
kindToggle: function (e) {
var id = e.currentTarget.id, list = this.data.list;
for (var i = 0, len = list.length; i < len; ++i) {
if (list[i].id == id) {
if(list[i].url){
wx.navigateTo({
url: 'pages/' + list[i].url
})
return
}
list[i].open = !list[i].open
} else {
list[i].open = false
}
}
this.setData({
list: list
});
}
})
b) .json
{
"navigationBarTitleText": "小程序接口能力展示"
}
c) .wxml
<view class="index">
<view class="index-hd">
<image class="index-logo" src="resources/kind/logo.png"></image>
<view class="index-desc">以下将演示小程序接口能力,具体属性参数详见小程序开发文档。</view>
</view>
<view class="index-bd">
<view class="kind-list">
<block wx:for-items="{{list}}" wx:key="{{item.id}}">
<view class="kind-list-item">
<view id="{{item.id}}" class="kind-list-item-hd {{item.open ? 'kind-list-item-hd-show' : ''}}" bindtap="kindToggle">
<view class="kind-list-text">{{item.name}}</view>
<image class="kind-list-img" src="resources/kind/{{item.id}}.png"></image>
</view>
<view class="kind-list-item-bd {{item.open ? 'kind-list-item-bd-show' : ''}}">
<view class="navigator-box {{item.open ? 'navigator-box-show' : ''}}">
<block wx:for-items="{{item.pages}}" wx:for-item="page" wx:key="*item">
<navigator url="pages/{{page.url}}" class="navigator">
<view class="navigator-text">{{page.zh}}</view>
<view class="navigator-arrow"></view>
</navigator>
</block>
</view>
</view>
</view>
</block>
</view>
</view>
</view>
d) .wxss
@import "../common/index.wxss";
e)
2、pages
3、resources
-kind
4、
2. api 开放接口返回顶部 |
1、login 微信登录
a) .js
var app = getApp()
Page({
onLoad: function () {
this.setData({
hasLogin: app.globalData.hasLogin
})
},
data: {},
login: function () {
var that = this
wx.login({
success: function (res) {
app.globalData.hasLogin = true
that.setData({
hasLogin: true
})
that.update()
}
})
}
})
b) .json
{
"navigationBarTitleText": "微信登录"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'Login'}}"/> <view class="page-body">
<view class="page-section">
<block wx:if="{{hasLogin === true}}">
<text class="page-body-title">已登录</text>
<text class="page-body-text">每个微信号中仅需登录 1 次,后续每次进入页面即可根据微信 id 自动拉取用户信息</text>
</block>
<block wx:if="{{hasLogin === false}}">
<text class="page-body-text">每个微信号中仅需登录一次</text>
<button class="page-body-button" type="primary" bindtap="login">微信登录</button>
</block>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.page-section {
margin-top: 200rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
padding: 0 50rpx;
box-sizing: border-box;
}
.page-body-title {
font-size: 60rpx;
line-height: 200rpx;
}
.page-body-text {
color: #bbb;
font-size: 28rpx;
line-height: 40rpx;
margin: 0 0 100rpx 0;
text-align: center;
}
.page-body-button {
width: 100%;
}
e)
2、get-user-info 获取用户信息
a) .js
var app = getApp()
Page({
data: {
hasUserInfo: false
},
getUserInfo: function () {
var that = this if (app.globalData.hasLogin === false) {
wx.login({
success: _getUserInfo
})
} else {
_getUserInfo()
} function _getUserInfo() {
wx.getUserInfo({
success: function (res) {
that.setData({
hasUserInfo: true,
userInfo: res.userInfo
})
that.update()
}
})
}
},
clear: function () {
this.setData({
hasUserInfo: false,
userInfo: {}
})
}
})
b) .json
{
"navigationBarTitleText": "获取用户信息"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'getUserInfo'}}"/> <view class="page-body">
<view class="page-section">
<view class="page-body-info">
<view class="page-body-title">用户信息</view>
<block wx:if="{{hasUserInfo === false}}">
<text class="page-body-text">未获取</text>
<text class="page-body-text">点击绿色按钮可获取用户头像及昵称</text>
</block>
<block wx:if="{{hasUserInfo === true}}">
<image class="userinfo-avatar" src="{{userInfo.avatarUrl}}"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
<view class="btn-area">
<button type="primary" bindtap="getUserInfo">获取用户信息</button>
<button bindtap="clear">清空</button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.page-body-info {
padding-bottom:;
height: 230px;
}
.userinfo-avatar {
border-radius: 128rpx;
width: 128rpx;
height: 128rpx;
}
.userinfo-nickname {
margin-top: 20rpx;
font-size: 38rpx;
}
e)
3、request-payment 发起支付
a) .js
const paymentUrl = require('../../../../config').paymentUrl var app = getApp() Page({
onLoad: function() {
},
requestPayment: function() {
var self = this self.setData({
loading: true
})
// 此处需要先调用wx.login方法获取code,然后在服务端调用微信接口使用code换取下单用户的openId
// 具体文档参考https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html?t=20161230#wxloginobject
app.getUserOpenId(function(err, openid) {
if (!err) {
wx.request({
url: paymentUrl,
data: {
openid
},
method: 'POST',
success: function(res) {
console.log('unified order success, response is:', res)
var payargs = res.data.payargs
wx.requestPayment({
timeStamp: payargs.timeStamp,
nonceStr: payargs.nonceStr,
package: payargs.package,
signType: payargs.signType,
paySign: payargs.paySign
}) self.setData({
loading: false
})
}
})
} else {
console.log('err:', err)
self.setData({
loading: false
})
}
})
}
})
b) .json
{
"navigationBarTitleText": "发起支付"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'requestPayment'}}"/> <view class="page-body">
<view class="page-section">
<view>支付金额</view>
<view class="price">0.01</view>
<view class="desc">实际接口应用中可自定义金额</view>
<view class="btn-area">
<button type="primary" bindtap="requestPayment" loading="{{loading}}">支付</button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.page-section{
width: auto;
margin: 30rpx;
padding: 64rpx 30rpx;
background-color: #fff;
text-align: center;
font-size: 28rpx;
}
.desc{
color: #B2B2B2;
}
.price{
margin-top: 30rpx;
margin-bottom: 25rpx;
position: relative;
display: inline-block;
font-size: 78rpx;
line-height:;
}
.price:before{
content: "¥";
position: absolute;
font-size: 40rpx;
top: 8rpx;
left: -40rpx;
}
e)
4、share 分享
a) .js
Page({
data: {
shareData: {
title: '自定义分享标题',
desc: '自定义分享描述',
path: '/page/API/pages/share/share'
}
},
onShareAppMessage: function () {
return this.data.shareData
}
})
b) .json
{
"navigationBarTitleText": "分享"
}
c) .wxml
<import src="../../../common/head.wxml"/>
<import src="../../../common/foot.wxml"/> <view class="container">
<template is="head" data="{{title: 'onShareAppMessage'}}"/> <view class="page-body">
<view class="weui-cells__title">发送内容(以下字段可自由适配)</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">标题</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="{{shareData.title}}"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">描述</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="{{shareData.desc}}"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">跳转页面</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="{{shareData.path}}"></input>
</view>
</view>
</view>
<view class="weui-cells__tips">点击右上角菜单分享给好友</view>
</view> <template is="foot"/>
</view>
d) .wxss
@import "../../../common/lib/weui.wxss";
e)
5、custom-message 客服消息
a) .js
Page({})
b) .json
{
"navigationBarTitleText":"客服消息"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'customMessage'}}"/> <view class="page-body">
<view class="page-body-wrapper">
<text class="page-body-title">
点击气泡icon打开客服消息界面
</text>
<view class="page-body-line">
<contact-button size="40" session-from="weapp"></contact-button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
/* page/API/pages/custom-message/custom-message.wxss */
e)
6、template-message 模板消息
a) .js
const templateMessageUrl = require('../../../../config').templateMessageUrl var app = getApp() const formData = {
address: 'T.I.T 造舰厂',
time: '2017.01.09',
name: '帝国歼星舰',
serial: '123456789'
} Page({
onLoad: function() {
this.setData({
formData
})
}, submitForm: function(e) {
var self = this
var form_id = e.detail.formId
var formData = e.detail.value console.log('form_id is:', form_id) self.setData({
loading: true
}) app.getUserOpenId(function(err, openid) {
if (!err) {
wx.request({
url: templateMessageUrl,
method: 'POST',
data: {
form_id,
openid,
formData
},
success: function(res) {
console.log('submit form success', res)
wx.showToast({
title: '发送成功',
icon: 'success'
})
self.setData({
loading: false
})
},
fail: function({errMsg}) {
console.log('submit form fail, errMsg is:', errMsg)
}
})
} else {
console.log('err:', err)
}
})
}
})
b) .json
{
"navigationBarTitleText": "模板消息"
}
c) .wxml
<import src="../../../common/head.wxml"/>
<import src="../../../common/foot.wxml"/> <view class="container">
<template is="head" data="{{title: 'templateMessage'}}"/>
<form class="page-body" bindsubmit="submitForm" report-submit="true">
<view class="weui-cells__title">点击提交,发送示例模板消息</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">购买地点</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="{{formData.address}}" name="address"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">购买时间</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="{{formData.time}}" name="time"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">物品名称</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="{{formData.name}}" name="name"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">交易单号</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="{{formData.serial}}" name="serial"></input>
</view>
</view>
</view>
<view class="btn-area">
<button type="primary" size="40" formType="submit" loading="{{loading}}">点我提交</button>
</view>
</form> <template is="foot" />
</view>
d) .wxss
@import "../../../common/lib/weui.wxss";
e)
7、
3. page 界面返回顶部 |
1、 set-navigation-bar-title 设置界面标题
a) .js
Page({
setNavigationBarTitle: function (e) {
var title = e.detail.value.title
console.log(title)
wx.setNavigationBarTitle({
title: title,
success: function() {
console.log('setNavigationBarTitle success')
},
fail: function(err) {
console.log('setNavigationBarTitle fail, err is', err)
}
}) return false
}
})
b) .json
{
"navigationBarTitleText":"设置界面标题"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'setNavigationBarTitle'}}"/> <form class="page-body" bindsubmit="setNavigationBarTitle">
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">页面标题</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" placeholder="请输入页面标题并点击设置即可" name="title"></input>
</view>
</view>
</view>
<view class="btn-area">
<button type="primary" formType="submit">设置</button>
</view>
</form> <template is="foot" />
</view>
d) .wxss
@import "../../../common/lib/weui.wxss"; .weui-label{
width: 5em;
}
e)
2、navigation-bar-loading 标题栏加载动画
a) .js
Page({
showNavigationBarLoading: function () {
wx.showNavigationBarLoading()
},
hideNavigationBarLoading: function () {
wx.hideNavigationBarLoading()
}
})
b) .json
{
"navigationBarTitleText": "标题栏加载动画"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'navigationBarLoading'}}"/> <view class="page-body">
<view class="btn-area">
<button type="primary" bindtap="showNavigationBarLoading">显示加载动画</button>
<button bindtap="hideNavigationBarLoading">隐藏加载动画</button>
</view>
</view> <template is="foot" />
</view>
d) .wxss
e)
3、navigator 页面跳转
a) .js
Page({
navigateTo: function () {
wx.navigateTo({ url: './navigator' })
},
navigateBack: function () {
wx.navigateBack()
},
redirectTo: function () {
wx.redirectTo({ url: './navigator' })
}
})
b) .json
{
"navigationBarTitleText": "页面跳转"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'navigateTo/Back, redirectTo'}}"/> <view class="page-body">
<view class="btn-area">
<button bindtap="navigateTo">跳转新页面</button>
<button bindtap="navigateBack">返回上一页</button>
<button bindtap="redirectTo">在当前页面打开</button>
</view>
</view> <template is="foot" />
</view>
d) .wxss
e)
4、pull-down-refrech 下拉刷新
a) .js
Page({
onPullDownRefresh: function () {
wx.showToast({
title: 'loading...',
icon: 'loading'
})
console.log('onPullDownRefresh', new Date())
},
stopPullDownRefresh: function () {
wx.stopPullDownRefresh({
complete: function (res) {
wx.hideToast()
console.log(res, new Date())
}
})
}
})
b) .json
{
"navigationBarTitleText": "下拉刷新",
"enablePullDownRefresh": true
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'on/stopPullDownRefresh'}}"/> <view class="page-body">
<view class="page-section">
<view class="page-body-info">
<text class="page-body-text">下滑页面即可刷新</text>
</view>
<view class="btn-area">
<button bindtap="stopPullDownRefresh">停止刷新</button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.page-body-info {
background-color: transparent;
}
.btn-area{
margin-top: 300rpx;
}
e)
5、animation 创建动画
a) .js
Page({
onReady: function () {
this.animation = wx.createAnimation()
},
rotate: function () {
this.animation.rotate(Math.random() * 720 - 360).step()
this.setData({animation: this.animation.export()})
},
scale: function () {
this.animation.scale(Math.random() * 2).step()
this.setData({animation: this.animation.export()})
},
translate: function () {
this.animation.translate(Math.random() * 100 - 50, Math.random() * 100 - 50).step()
this.setData({animation: this.animation.export()})
},
skew: function () {
this.animation.skew(Math.random() * 90, Math.random() * 90).step()
this.setData({animation: this.animation.export()})
},
rotateAndScale: function () {
this.animation.rotate(Math.random() * 720 - 360)
.scale(Math.random() * 2)
.step()
this.setData({animation: this.animation.export()})
},
rotateThenScale: function () {
this.animation.rotate(Math.random() * 720 - 360).step()
.scale(Math.random() * 2).step()
this.setData({animation: this.animation.export()})
},
all: function () {
this.animation.rotate(Math.random() * 720 - 360)
.scale(Math.random() * 2)
.translate(Math.random() * 100 - 50, Math.random() * 100 - 50)
.skew(Math.random() * 90, Math.random() * 90)
.step()
this.setData({animation: this.animation.export()})
},
allInQueue: function () {
this.animation.rotate(Math.random() * 720 - 360).step()
.scale(Math.random() * 2).step()
.translate(Math.random() * 100 - 50, Math.random() * 100 - 50).step()
.skew(Math.random() * 90, Math.random() * 90).step()
this.setData({animation: this.animation.export()})
},
reset: function () {
this.animation.rotate(0, 0)
.scale(1)
.translate(0, 0)
.skew(0, 0)
.step({duration: 0})
this.setData({animation: this.animation.export()})
}
})
b) .json
{
"navigationBarTitleText": "动画"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'createAnimation'}}"/> <view class="page-body">
<view class="page-section"> <view class="animation-element-wrapper">
<view class="animation-element" animation="{{animation}}"></view>
</view>
<scroll-view class="animation-buttons" scroll-y="true">
<button class="animation-button" bindtap="rotate">旋转</button>
<button class="animation-button" bindtap="scale">缩放</button>
<button class="animation-button" bindtap="translate">移动</button>
<button class="animation-button" bindtap="skew">倾斜</button>
<button class="animation-button" bindtap="rotateAndScale">旋转并缩放</button>
<button class="animation-button" bindtap="rotateThenScale">旋转后缩放</button>
<button class="animation-button" bindtap="all">同时展示全部</button>
<button class="animation-button" bindtap="allInQueue">顺序展示全部</button>
<button class="animation-button animation-button-reset" bindtap="reset">还原</button>
</scroll-view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.animation-element-wrapper {
display: flex;
width: 100%;
padding-top: 150rpx;
padding-bottom: 150rpx;
justify-content: center;
overflow: hidden;
background-color: #ffffff;
}
.animation-element {
width: 200rpx;
height: 200rpx;
background-color: #1AAD19;
}
.animation-buttons {
padding: 30rpx 50rpx 10rpx;
width: 100%;
height: 360rpx;
box-sizing: border-box;
}
.animation-button {
float: left;
line-height:;
width: 300rpx;
margin: 15rpx 12rpx;
} .animation-button-reset {
width: 620rpx;
}
e)
6、创建绘画
0、
1、view
a) .js
var example = require('./example.js') Page({
onLoad: function () {
this.context = wx.createContext() var methods = Object.keys(example)
this.setData({
methods: methods
}) var that = this
methods.forEach(function (method) {
that[method] = function () {
example[method](that.context)
var actions = that.context.getActions() wx.drawCanvas({
canvasId: 'canvas',
actions: actions
})
}
})
},
toTempFilePath: function () {
wx.canvasToTempFilePath({
canvasId: 'canvas',
success: function (res) {
console.log(res)
},
fail: function (res) {
console.log(res)
}
})
}
})
b) .json
{
"navigationBarTitleText": "创建画布"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'createContext'}}"/> <view class="page-body">
<view class="page-section">
<canvas class="canvas-element" canvas-id="canvas"></canvas>
<scroll-view class="canvas-buttons" scroll-y="true">
<block wx:for="{{methods}}" wx:for-item="method">
<button class="canvas-button" bindtap="{{method}}">{{method}}</button>
</block>
<button class="canvas-button" bindtap="toTempFilePath" type="primary">toTempFilePath</button>
</scroll-view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.canvas-element-wrapper {
display: block;
margin-bottom: 100rpx;
}
.canvas-element {
width: 100%;
height: 500rpx;
background-color: #ffffff;
}
.canvas-buttons {
padding: 30rpx 50rpx 10rpx;
width: 100%;
height: 360rpx;
box-sizing: border-box;
}
.canvas-button {
float: left;
line-height:;
width: 300rpx;
margin: 15rpx 12rpx;
}
e) example.js
var example = {} example.rotate = function (context) {
context.beginPath()
context.rotate(10 * Math.PI / 180)
context.rect(225, 75, 20, 10)
context.fill()
} example.scale = function (context) {
context.beginPath()
context.rect(25, 25, 50, 50)
context.stroke() context.scale(2, 2) context.beginPath()
context.rect(25, 25, 50, 50)
context.stroke()
} example.reset = function (context) {
context.beginPath() context.setFillStyle('#000000')
context.setStrokeStyle('#000000')
context.setFontSize(10) context.setShadow(0, 0, 0, 'rgba(0, 0, 0, 0)') context.setLineCap('butt')
context.setLineJoin('miter')
context.setLineWidth(1)
context.setMiterLimit(10)
} example.translate = function (context) {
context.beginPath()
context.rect(10, 10, 100, 50)
context.fill() context.translate(70, 70) context.beginPath()
context.fill()
} example.save = function (context) {
context.beginPath()
context.setStrokeStyle('#00ff00')
context.save() context.scale(2, 2)
context.setStrokeStyle('#ff0000')
context.rect(0, 0, 100, 100)
context.stroke()
context.restore() context.rect(0, 0, 50, 50)
context.stroke()
} example.restore = function (context) {
[3, 2, 1].forEach(function (item) {
context.beginPath()
context.save()
context.scale(item, item)
context.rect(10, 10, 100, 100)
context.stroke()
context.restore()
})
} example.drawImage = function (context) {
context.drawImage('/image/wechat.png', 0, 0)
} example.fillText = function (context) {
context.setStrokeStyle('#ff0000') context.beginPath()
context.moveTo(0, 10)
context.lineTo(300, 10)
context.stroke() // context.save()
// context.scale(1.5, 1.5)
// context.translate(20, 20)
context.setFontSize(10)
context.fillText('Hello World', 0, 30)
context.setFontSize(20)
context.fillText('Hello World', 100, 30) // context.restore() context.beginPath()
context.moveTo(0, 30)
context.lineTo(300, 30)
context.stroke()
} example.fill = function (context) {
context.beginPath()
context.rect(20, 20, 150, 100)
context.setStrokeStyle('#00ff00')
context.fill()
} example.stroke = function (context) {
context.beginPath()
context.moveTo(20, 20)
context.lineTo(20, 100)
context.lineTo(70, 100)
context.setStrokeStyle('#00ff00')
context.stroke()
} example.clearRect = function (context) {
context.setFillStyle('#ff0000')
context.beginPath()
context.rect(0, 0, 300, 150)
context.fill()
context.clearRect(20, 20, 100, 50)
} example.beginPath = function (context) {
context.beginPath()
context.setLineWidth(5)
context.setStrokeStyle('#ff0000')
context.moveTo(0, 75)
context.lineTo(250, 75)
context.stroke() context.beginPath()
context.setStrokeStyle('#0000ff')
context.moveTo(50, 0)
context.lineTo(150, 130)
context.stroke()
} example.closePath = function (context) {
context.beginPath()
context.moveTo(20, 20)
context.lineTo(20, 100)
context.lineTo(70, 100)
context.closePath()
context.stroke()
} example.moveTo = function (context) {
context.beginPath()
context.moveTo(0, 0)
context.lineTo(300, 150)
context.stroke()
} example.lineTo = function (context) {
context.beginPath()
context.moveTo(20, 20)
context.lineTo(20, 100)
context.lineTo(70, 100)
context.stroke()
} example.rect = function (context) {
context.beginPath()
context.rect(20, 20, 150, 100)
context.stroke()
} example.arc = function (context) {
context.beginPath()
context.arc(75, 75, 50, 0, Math.PI * 2, true)
context.moveTo(110, 75)
context.arc(75, 75, 35, 0, Math.PI, false)
context.moveTo(65, 65)
context.arc(60, 65, 5, 0, Math.PI * 2, true)
context.moveTo(95, 65)
context.arc(90, 65, 5, 0, Math.PI * 2, true)
context.stroke()
} example.quadraticCurveTo = function (context) {
context.beginPath()
context.moveTo(20, 20)
context.quadraticCurveTo(20, 100, 200, 20)
context.stroke()
} example.bezierCurveTo = function (context) {
context.beginPath()
context.moveTo(20, 20)
context.bezierCurveTo(20, 100, 200, 100, 200, 20)
context.stroke()
} example.setFillStyle = function (context) {
['#fef957', 'rgb(242,159,63)', 'rgb(242,117,63)', '#e87e51'].forEach(function (item, index) {
context.setFillStyle(item)
context.beginPath()
context.rect(0 + 75 * index, 0, 50, 50)
context.fill()
})
} example.setStrokeStyle = function (context) {
['#fef957', 'rgb(242,159,63)', 'rgb(242,117,63)', '#e87e51'].forEach(function (item, index) {
context.setStrokeStyle(item)
context.beginPath()
context.rect(0 + 75 * index, 0, 50, 50)
context.stroke()
})
} example.setGlobalAlpha = function (context) {
context.setFillStyle('#000000');
[1, 0.5, 0.1].forEach(function (item, index) {
context.setGlobalAlpha(item)
context.beginPath()
context.rect(0 + 75 * index, 0, 50, 50)
context.fill()
})
} example.setShadow = function (context) {
context.beginPath()
context.setShadow(10, 10, 10, 'rgba(0, 0, 0, 199)')
context.rect(10, 10, 100, 100)
context.fill()
} example.setFontSize = function (context) {
[10, 20, 30, 40].forEach(function (item, index) {
context.setFontSize(item)
context.fillText('Hello, world', 20, 20 + 40*index)
})
} example.setLineCap = function (context) {
context.setLineWidth(10);
['butt', 'round', 'square'].forEach(function (item, index) {
context.beginPath()
context.setLineCap(item)
context.moveTo(20, 20 + 20*index)
context.lineTo(100, 20 + 20*index)
context.stroke()
})
} example.setLineJoin = function (context) {
context.setLineWidth(10);
['bevel', 'round', 'miter'].forEach(function (item, index) {
context.beginPath() context.setLineJoin(item)
context.moveTo(20 + 80 * index, 20)
context.lineTo(100 + 80 * index, 50)
context.lineTo(20 + 80 * index, 100)
context.stroke()
})
} example.setLineWidth = function (context) {
[2, 4, 6, 8, 10].forEach(function (item, index) {
context.beginPath()
context.setLineWidth(item)
context.moveTo(20, 20 + 20 * index)
context.lineTo(100, 20 + 20 * index)
context.stroke()
})
} example.setMiterLimit = function (context) {
context.setLineWidth(4); [2, 4, 6, 8, 10].forEach(function (item, index) {
context.beginPath()
context.setMiterLimit(item)
context.moveTo(20 + 80 * index, 20)
context.lineTo(100 + 80 * index, 50)
context.lineTo(20 + 80 * index, 100)
context.stroke()
})
} module.exports = example
f)
7、action-sheet 显示操作菜单
a) .js
Page({
actionSheetTap: function () {
wx.showActionSheet({
itemList: ['item1', 'item2', 'item3', 'item4'],
success: function (e) {
console.log(e.tapIndex)
}
})
}
})
b) .json
{
"navigationBarTitleText": "操作菜单"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'action-sheet'}}"/> <view class="page-body">
<view class="btn-area">
<button type="default" bindtap="actionSheetTap">弹出action sheet</button>
</view>
</view> <template is="foot" />
</view>
d) .wxss
/*
.cancel {
color: white;
background: #303F9F;
}
.item {
color: black;
background: #C5CAE9;
}*/
e)
8、model 显示模态弹出
a) .js
Page({
data: {
modalHidden: true,
modalHidden2: true
},
modalTap: function(e) {
wx.showModal({
title: "弹窗标题",
content: "弹窗内容,告知当前状态、信息和解决方法,描述文字尽量控制在三行内",
showCancel: false,
confirmText: "确定"
})
},
noTitlemodalTap: function(e) {
wx.showModal({
content: "弹窗内容,告知当前状态、信息和解决方法,描述文字尽量控制在三行内",
confirmText: "确定",
cancelText: "取消"
})
}
})
b) .json
{
"navigationBarTitleText": "模态弹窗"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'modal'}}"/> <view class="page-body">
<view class="btn-area">
<button type="default" bindtap="modalTap">有标题的modal</button>
<button type="default" bindtap="noTitlemodalTap">无标题的modal</button>
</view>
</view> <template is="foot" />
</view>
d) .wxss
/* page/API/pages/modal/modal.wxss */
e)
9、toast 显示消息提示框
a) .js
Page({
toast1Tap: function () {
wx.showToast({
title: "默认"
})
},
toast2Tap: function () {
wx.showToast({
title: "duration 3000",
duration: 3000
})
},
toast3Tap: function () {
wx.showToast({
title: "loading",
icon: "loading",
duration: 5000
})
},
hideToast: function () {
wx.hideToast()
}
})
b) .json
{
"navigationBarTitleText": "消息提示框"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'toast'}}"/> <view class="page-body">
<view class="btn-area">
<view class="body-view">
<button type="default" bindtap="toast1Tap">点击弹出默认toast</button>
</view>
<view class="body-view">
<button type="default" bindtap="toast2Tap">点击弹出设置duration的toast</button>
</view>
<view class="body-view">
<button type="default" bindtap="toast3Tap">点击弹出显示loading的toast</button>
</view>
<view class="body-view">
<button type="default" bindtap="hideToast">点击隐藏toast</button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
/* page/API/pages/toast/toast.wxss */
e)
10、
4. device 设备返回顶部 |
1、get-network-type 获取手机网络状态
a) .js
Page({
data: {
hasNetworkType: false
},
getNetworkType: function () {
var that = this
wx.getNetworkType({
success: function (res) {
console.log(res)
that.setData({
hasNetworkType: true,
networkType: res.subtype || res.networkType
})
that.update()
}
})
},
clear: function () {
this.setData({
hasNetworkType: false,
networkType: ''
})
}
})
b) .json
{
"navigationBarTitleText": "获取手机网络状态"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'getNetworkType'}}"/> <view class="page-body">
<view class="page-section">
<view class="page-body-info">
<view class="page-body-title">网络状态</view>
<block wx:if="{{hasNetworkType === false}}">
<text class="page-body-text">未获取</text>
<text class="page-body-text">点击绿色按钮可获取网络状态</text>
</block>
<block wx:if="{{hasNetworkType === true}}">
<text class="page-body-text-network-type">{{networkType}}</text>
</block>
</view>
<view class="btn-area">
<button type="primary" bindtap="getNetworkType">获取手机网络状态</button>
<button bindtap="clear">清空</button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.page-body-info {
height: 200rpx;
}
.page-body-text-network-type {
font-size: 80rpx;
font-family: -apple-system-font,Helvetica Neue,Helvetica,sans-serif;
}
e)
2、get-system-info 获取手机系统信息
a) .js
Page({
data: {
systemInfo: {}
},
getSystemInfo: function () {
var that = this
wx.getSystemInfo({
success: function (res) {
that.setData({
systemInfo: res
})
that.update()
}
})
}
})
b) .json
{
"navigationBarTitleText": "获取手机系统信息"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'getSystemInfo'}}"/> <view class="page-body">
<view class="page-section">
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">手机型号</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" placeholder="未获取" value="{{systemInfo.model}}"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">微信语言</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" placeholder="未获取" value="{{systemInfo.language}}"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">微信版本</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" placeholder="未获取" value="{{systemInfo.version}}"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">屏幕宽度</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" placeholder="未获取" value="{{systemInfo.windowWidth}}"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">屏幕高度</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" placeholder="未获取" value="{{systemInfo.windowHeight}}"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">DPI</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" placeholder="未获取" value="{{systemInfo.pixelRatio}}"></input>
</view>
</view>
</view>
<view class="btn-area">
<button type="primary" bindtap="getSystemInfo">获取手机系统信息</button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
@import "../../../common/lib/weui.wxss";
e)
3、on-accelerometer-change 监听重力感应数据
a) .js
Page({
onReady: function () {
this.drawBigBall()
var that = this this.position = {
x: 151,
y: 151,
vx: 0,
vy: 0,
ax: 0,
ay: 0
}
wx.onAccelerometerChange(function (res) {
that.setData({
x: res.x.toFixed(2),
y: res.y.toFixed(2),
z: res.z.toFixed(2)
})
that.position.ax = Math.sin(res.x * Math.PI / 2)
that.position.ay = -Math.sin(res.y * Math.PI / 2)
//that.drawSmallBall()
}) this.interval = setInterval(function () {
that.drawSmallBall()
}, 17) },
drawBigBall: function () {
var context = wx.createContext()
context.beginPath(0)
context.arc(151, 151, 140, 0, Math.PI * 2)
context.setFillStyle('#ffffff')
context.setStrokeStyle('#aaaaaa')
context.fill()
// context.stroke()
wx.drawCanvas({
canvasId: 'big-ball',
actions: context.getActions()
})
},
drawSmallBall: function () {
var p = this.position
var strokeStyle = 'rgba(1,1,1,0)' p.x = p.x + p.vx
p.y = p.y + p.vy
p.vx = p.vx + p.ax
p.vy = p.vy + p.ay if (Math.sqrt(Math.pow(Math.abs(p.x) - 151, 2) + Math.pow(Math.abs(p.y) - 151, 2)) >= 115) {
if (p.x > 151 && p.vx > 0) {
p.vx = 0
}
if (p.x < 151 && p.vx < 0) {
p.vx = 0
}
if (p.y > 151 && p.vy > 0) {
p.vy = 0
}
if (p.y < 151 && p.vy < 0) {
p.vy = 0
}
strokeStyle = '#ff0000'
} var context = wx.createContext()
context.beginPath(0)
context.arc(p.x, p.y, 15, 0, Math.PI * 2)
context.setFillStyle('#1aad19')
context.setStrokeStyle(strokeStyle)
context.fill()
// context.stroke()
wx.drawCanvas({
canvasId: 'small-ball',
actions: context.getActions()
})
},
data: {
x: 0,
y: 0,
z: 0
},
onUnload: function () {
clearInterval(this.interval)
}
})
b) .json
{
"navigationBarTitleText": "监听重力感应数据"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'onAccelerometerChange'}}"/> <view class="page-body">
<view class="page-section page-section_center">
<text class="page-body-text">倾斜手机即可移动下方小球</text>
<view class="page-body-canvas">
<canvas class="page-body-ball" show="{{true}}" canvas-id="big-ball"></canvas>
<canvas class="page-body-ball" show="{{true}}" canvas-id="small-ball"></canvas>
</view>
<view class="page-body-xyz">
<text class="page-body-title">X: {{x}}</text>
<text class="page-body-title">Y: {{y}}</text>
<text class="page-body-title">Z: {{z}}</text>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.page-body-xyz {
display: flex;
justify-content: space-between;
width: 700rpx;
margin-top: 90rpx;
box-sizing: border-box;
text-align: center;
}
.page-body-canvas {
margin-top: 30rpx;
width: 302px;
height: 302px;
position: relative;
}
.page-body-ball {
position: absolute;
top:;
left:;
width: 302px;
height: 302px;
}
.page-body-title {
margin-bottom:;
font-size: 32rpx;
width: 250rpx;
}
e)
4、on-compass-change 监听罗盘数据
0、
a) .js
Page({
data: {
direction: 0
},
onReady: function () {
var that = this
wx.onCompassChange(function (res) {
that.setData({
direction: parseInt(res.direction)
})
})
}
})
b) .json
{
"navigationBarTitleText": "监听罗盘数据"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'onCompassChange'}}"/> <view class="page-body">
<view class="page-section page-section_center">
<text class="page-body-text">旋转手机即可获取方位信息</text>
<view class="direction">
<view class="bg-compass-line"></view>
<image class="bg-compass" src="compass.png" style="transform: rotate({{direction}}deg)"></image>
<view class="direction-value">
<text>{{direction}}</text>
<text class="direction-degree">o</text>
</view>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.direction {
position: relative;
margin-top: 70rpx;
display: flex;
width: 540rpx;
height: 540rpx;
align-items: center;
justify-content: center;
}
.direction-value {
position: relative;
font-size: 200rpx;
color: #353535;
line-height:;
z-index:;
}
.direction-degree {
position: absolute;
top:;
right: -40rpx;
font-size: 60rpx;
}
.bg-compass{
position: absolute;
top:;
left:;
width: 540rpx;
height: 540rpx;
transition: .1s;
}
.bg-compass-line{
position: absolute;
left: 267rpx;
top: -10rpx;
width: 6rpx;
height: 56rpx;
background-color: #1AAD19;
border-radius: 999rpx;
z-index:;
}
e)
5、make-phone-call 打电话
a) .js
Page({
data: {
disabled: true
},
bindInput: function(e) {
this.inputValue = e.detail.value if (this.inputValue.length > 0) {
this.setData({
disabled: false
})
} else {
this.setData({
disabled: true
})
}
},
makePhoneCall: function () {
var that = this
wx.makePhoneCall({
phoneNumber: this.inputValue,
success: function () {
console.log("成功拨打电话")
}
})
}
})
b) .json
{
"navigationBarTitleText": "打电话"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'makePhoneCall'}}"/> <view class="page-body">
<view class="page-section">
<view class="desc">请在下方输入电话号码</view>
<input class="input" type="number" name="input" bindinput="bindInput" />
<view class="btn-area">
<button type="primary" bindtap="makePhoneCall" disabled="{{disabled}}">拨打</button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.page-section{
width: auto;
margin: 30rpx;
padding: 44rpx 60rpx 60rpx;
background-color: #fff;
font-size: 28rpx;
}
.desc{
margin-bottom: 20rpx;
}
.input{
height: 119rpx;
line-height: 119rpx;
font-size: 78rpx;
border-bottom: 1rpx solid #E2E2E2;
}
.btn-area{
padding:;
}
e)
6、scan-code 扫码
a) .js
Page({
data: {
result: ''
},
scanCode: function () {
var that = this
wx.scanCode({
success: function (res) {
that.setData({
result: res.result
})
},
fail: function (res) {
}
})
}
})
b) .json
{
"navigationBarTitleText": "扫码"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'scanCode'}}"/> <view class="page-body">
<view class="weui-cells__title">扫码结果</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell">
<view class="weui-cell__bd">{{result}}</view>
</view>
</view>
<view class="btn-area">
<button type="primary" bindtap="scanCode">扫一扫</button>
</view>
</view> <template is="foot" />
</view>
d) .wxss
@import "../../../common/lib/weui.wxss"; .weui-cell__bd{
min-height: 48rpx;
word-break: break-all;
}
e)
7、
5. network 网络返回顶部 |
1、发起一个请求
a) .js
const requestUrl = require('../../../../config').requestUrl
const duration = 2000 Page({
makeRequest: function() {
var self = this self.setData({
loading: true
}) wx.request({
url: requestUrl,
data: {
noncestr: Date.now()
},
success: function(result) {
wx.showToast({
title: '请求成功',
icon: 'success',
mask: true,
duration: duration
})
self.setData({
loading: false
})
console.log('request success', result)
}, fail: function({errMsg}) {
console.log('request fail', errMsg)
self.setData({
loading: false
})
}
})
}
})
b) .json
{
"navigationBarTitleText": "网络请求"
}
c) .wxml
<import src="../../../common/head.wxml"/>
<import src="../../../common/foot.wxml"/> <view class="container">
<template is="head" data="{{title: 'request'}}"/> <view class="page-body">
<view class="page-body-wording">
<text class="page-body-text">
点击向服务器发起请求
</text>
</view>
<view class="btn-area">
<button bindtap="makeRequest" type="primary" disabled="{{buttonDisabled}}" loading="{{loading}}">request</button>
</view>
</view> <template is="foot"/>
</view>
d) .wxss
e)
2、WebSocket
a) .js
const qcloud = require('../../../../vendor/qcloud-weapp-client-sdk/index')
const loginUrl = require('../../../../config').loginUrl
const tunnelUrl = require('../../../../config').tunnelUrl function showModal(title, content) {
wx.showModal({
title,
content,
showCancel: false
})
} function showSuccess(title) {
wx.showToast({
title,
icon: 'success',
duration: 1000
})
} Page({
data: {
socketStatus: 'closed'
}, onLoad: function() {
var self = this qcloud.setLoginUrl(loginUrl) qcloud.login({
success: function(result) {
console.log('登录成功', result)
self.setData({
hasLogin: true
})
}, fail: function(error) {
console.log('登录失败', error)
}
})
}, onUnload: function() {
this.closeSocket()
}, toggleSocket: function(e) {
const turnedOn = e.detail.value if (turnedOn && this.data.socketStatus == 'closed') {
this.openSocket() } else if (!turnedOn && this.data.socketStatus == 'connected') {
var showSuccess = true
this.closeSocket(showSuccess)
}
}, openSocket: function() {
var socket = this.socket = new qcloud.Tunnel(tunnelUrl) socket.on('connect', () => {
console.log('WebSocket 已连接')
showSuccess('Socket已连接')
this.setData({
socketStatus: 'connected',
waitingResponse: false
})
}) socket.on('close', () => {
console.log('WebSocket 已断开')
this.setData({ socketStatus: 'closed' })
}) socket.on('error', error => {
showModal('发生错误', JSON.stringify(error))
console.error('socket error:', error)
this.setData({
loading: false
})
}) // 监听服务器推送消息
socket.on('message', message => {
showSuccess('收到信道消息')
console.log('socket message:', message)
this.setData({
loading: false
})
}) // 打开信道
socket.open()
}, closeSocket: function(showSuccessToast) {
if (this.socket) {
this.socket.close()
}
if (showSuccessToast) showSuccess('Socket已断开')
this.setData({ socketStatus: 'closed' })
}, sendMessage: function() {
if (this.socket && this.socket.isActive()) {
this.socket.emit('message', {
'content': 'Hello, 小程序!'
})
this.setData({
loading: true
})
}
},
})
b) .json
{
"navigationBarTitleText": "Web Socket"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'WebSocket'}}"/> <view class="page-body">
<view class="page-section">
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_switch">
<view class="weui-cell__bd">Socket状态</view>
<view class="weui-cell__ft">
<switch bindchange="toggleSocket" disabled="{{!hasLogin}}"/>
</view>
</view>
<view class="weui-cell">
<view class="weui-cell__bd">消息</view>
<view class="weui-cell__ft">
Hello, 小程序!
</view>
</view>
</view>
</view>
<view class="btn-area">
<button type="primary" size="40" bindtap="sendMessage" disabled="{{socketStatus != 'connected'}}" loading="{{loading}}">点我发送</button>
</view>
</view> <template is="foot" />
</view>
d) .wxss
@import "../../../common/lib/weui.wxss";
e)
3、upload-file 上传文件
a) .js
const uploadFileUrl = require('../../../../config').uploadFileUrl Page({
chooseImage: function() {
var self = this wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album'],
success: function(res) {
console.log('chooseImage success, temp path is', res.tempFilePaths[0]) var imageSrc = res.tempFilePaths[0] wx.uploadFile({
url: uploadFileUrl,
filePath: imageSrc,
name: 'data',
success: function(res) {
console.log('uploadImage success, res is:', res) wx.showToast({
title: '上传成功',
icon: 'success',
duration: 1000
}) self.setData({
imageSrc
})
},
fail: function({errMsg}) {
console.log('uploadImage fail, errMsg is', errMsg)
}
}) },
fail: function({errMsg}) {
console.log('chooseImage fail, err is', errMsg)
}
})
}
})
b) .json
{
"navigationBarTitleText": "上传文件"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'uploadFile'}}"/> <view class="page-body">
<view class="page-section">
<view class="page-body-info"> <block wx:if="{{imageSrc}}">
<image src="{{imageSrc}}" class="image" mode="aspectFit"></image>
</block> <block wx:else>
<view class="image-plus image-plus-nb" bindtap="chooseImage">
<view class="image-plus-horizontal"></view>
<view class="image-plus-vertical"></view>
</view>
<view class="image-plus-text">选择图片</view>
</block> </view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.image {
width: 100%;
height: 360rpx;
}
.page-body-info {
display: flex;
box-sizing: border-box;
padding: 30rpx;
height: 420rpx;
border-top: 1rpx solid #D9D9D9;
border-bottom: 1rpx solid #D9D9D9;
align-items: center;
justify-content: center;
}
e)
4、download-file 下载文件
a) .js
const downloadExampleUrl = require('../../../../config').downloadExampleUrl Page({
downloadImage: function() {
var self = this wx.downloadFile({
url: downloadExampleUrl,
success: function(res) {
console.log('downloadFile success, res is', res) self.setData({
imageSrc: res.tempFilePath
})
},
fail: function({errMsg}) {
console.log('downloadFile fail, err is:', errMsg)
}
})
}
})
b) .json
{
"navigationBarTitleText": "下载文件"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'downloadFile'}}"/> <view class="page-body">
<image wx:if="{{imageSrc}}" src="{{imageSrc}}" mode="center" />
<block wx:else>
<view class="page-body-wording">
<text class="page-body-text">
点击按钮下载服务端示例图片
</text>
</view>
<view class="btn-area">
<button bindtap="downloadImage" type="primary">下载</button>
</view>
</block>
</view> <template is="foot" />
</view>
d) .wxss
.page-body image {
width: 600rpx;
height: 600rpx; margin: 0 75rpx;
}
e)
5、
6. media 媒体返回顶部 |
1、image 图片
a) .js
var sourceType = [ ['camera'], ['album'], ['camera', 'album'] ]
var sizeType = [ ['compressed'], ['original'], ['compressed', 'original'] ] Page({
data: {
imageList: [],
sourceTypeIndex: 2,
sourceType: ['拍照', '相册', '拍照或相册'], sizeTypeIndex: 2,
sizeType: ['压缩', '原图', '压缩或原图'], countIndex: 8,
count: [1, 2, 3, 4, 5, 6, 7, 8, 9]
},
sourceTypeChange: function (e) {
this.setData({
sourceTypeIndex: e.detail.value
})
},
sizeTypeChange: function (e) {
this.setData({
sizeTypeIndex: e.detail.value
})
},
countChange: function (e) {
this.setData({
countIndex: e.detail.value
})
},
chooseImage: function () {
var that = this
wx.chooseImage({
sourceType: sourceType[this.data.sourceTypeIndex],
sizeType: sizeType[this.data.sizeTypeIndex],
count: this.data.count[this.data.countIndex],
success: function (res) {
console.log(res)
that.setData({
imageList: res.tempFilePaths
})
}
})
},
previewImage: function (e) {
var current = e.target.dataset.src wx.previewImage({
current: current,
urls: this.data.imageList
})
}
})
b) .json
{
"navigationBarTitleText": "图片"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'choose/previewImage'}}"/> <view class="page-body">
<form>
<view class="page-section"> <view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">图片来源</view>
</view>
<view class="weui-cell__bd">
<picker range="{{sourceType}}" bindchange="sourceTypeChange" value="{{sourceTypeIndex}}" mode="selector">
<view class="weui-input">{{sourceType[sourceTypeIndex]}}</view>
</picker>
</view>
</view> <view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">图片质量</view>
</view>
<view class="weui-cell__bd">
<picker range="{{sizeType}}" bindchange="sizeTypeChange" value="{{sizeTypeIndex}}" mode="selector">
<view class="weui-input">{{sizeType[sizeTypeIndex]}}</view>
</picker>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">数量限制</view>
</view>
<view class="weui-cell__bd">
<picker range="{{count}}" bindchange="countChange" value="{{countIndex}}" mode="selector">
<view class="weui-input">{{count[countIndex]}}</view>
</picker>
</view>
</view>
</view> <view class="weui-cells">
<view class="weui-cell">
<view class="weui-cell__bd">
<view class="weui-uploader">
<view class="weui-uploader__hd">
<view class="weui-uploader__title">点击可预览选好的图片</view>
<view class="weui-uploader__info">{{imageList.length}}/{{count[countIndex]}}</view>
</view>
<view class="weui-uploader__bd">
<view class="weui-uploader__files">
<block wx:for="{{imageList}}" wx:for-item="image">
<view class="weui-uploader__file">
<image class="weui-uploader__img" src="{{image}}" data-src="{{image}}" bindtap="previewImage"></image>
</view>
</block>
</view>
<view class="weui-uploader__input-box">
<view class="weui-uploader__input" bindtap="chooseImage"></view>
</view>
</view>
</view>
</view>
</view>
</view> </view>
</form>
</view> <template is="foot" />
</view>
d) .wxss
@import "../../../common/lib/weui.wxss";
e)
2、voice 录音
a) .js
var util = require('../../../../util/util.js')
var playTimeInterval
var recordTimeInterval Page({
data: {
recording: false,
playing: false,
hasRecord: false,
recordTime: 0,
playTime: 0,
formatedRecordTime: '00:00:00',
formatedPlayTime: '00:00:00'
},
onHide: function() {
if (this.data.playing) {
this.stopVoice()
} else if (this.data.recording) {
this.stopRecordUnexpectedly()
}
},
startRecord: function () {
this.setData({ recording: true }) var that = this
recordTimeInterval = setInterval(function () {
var recordTime = that.data.recordTime += 1
that.setData({
formatedRecordTime: util.formatTime(that.data.recordTime),
recordTime: recordTime
})
}, 1000)
wx.startRecord({
success: function (res) {
that.setData({
hasRecord: true,
tempFilePath: res.tempFilePath,
formatedPlayTime: util.formatTime(that.data.playTime)
})
},
complete: function () {
that.setData({ recording: false })
clearInterval(recordTimeInterval)
}
})
},
stopRecord: function() {
wx.stopRecord()
},
stopRecordUnexpectedly: function () {
var that = this
wx.stopRecord({
success: function() {
console.log('stop record success')
clearInterval(recordTimeInterval)
that.setData({
recording: false,
hasRecord: false,
recordTime: 0,
formatedRecordTime: util.formatTime(0)
})
}
})
},
playVoice: function () {
var that = this
playTimeInterval = setInterval(function () {
var playTime = that.data.playTime + 1
console.log('update playTime', playTime)
that.setData({
playing: true,
formatedPlayTime: util.formatTime(playTime),
playTime: playTime
})
}, 1000)
wx.playVoice({
filePath: this.data.tempFilePath,
success: function () {
clearInterval(playTimeInterval)
var playTime = 0
console.log('play voice finished')
that.setData({
playing: false,
formatedPlayTime: util.formatTime(playTime),
playTime: playTime
})
}
})
},
pauseVoice: function () {
clearInterval(playTimeInterval)
wx.pauseVoice()
this.setData({
playing: false
})
},
stopVoice: function () {
clearInterval(playTimeInterval)
this.setData({
playing: false,
formatedPlayTime: util.formatTime(0),
playTime: 0
})
wx.stopVoice()
},
clear: function () {
clearInterval(playTimeInterval)
wx.stopVoice()
this.setData({
playing: false,
hasRecord: false,
tempFilePath: '',
formatedRecordTime: util.formatTime(0),
recordTime: 0,
playTime: 0
})
}
})
b) .json
{
"navigationBarTitleText": "录音"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'start/stopRecord、play/stopVoice'}}"/> <view class="page-body">
<view class="page-section">
<block wx:if="{{recording === false && playing === false && hasRecord === false}}">
<view class="page-body-time">
<text class="time-big">{{formatedRecordTime}}</text>
</view>
<view class="page-body-buttons">
<view class="page-body-button"></view>
<view class="page-body-button" bindtap="startRecord">
<image src="/image/record.png"></image>
</view>
<view class="page-body-button"></view>
</view>
</block> <block wx:if="{{recording === true}}">
<view class="page-body-time">
<text class="time-big">{{formatedRecordTime}}</text>
</view>
<view class="page-body-buttons">
<view class="page-body-button"></view>
<view class="page-body-button" bindtap="stopRecord">
<view class="button-stop-record"></view>
</view>
<view class="page-body-button"></view>
</view>
</block> <block wx:if="{{hasRecord === true && playing === false}}">
<view class="page-body-time">
<text class="time-big">{{formatedPlayTime}}</text>
<text class="time-small">{{formatedRecordTime}}</text>
</view>
<view class="page-body-buttons">
<view class="page-body-button"></view>
<view class="page-body-button" bindtap="playVoice">
<image src="/image/play.png"></image>
</view>
<view class="page-body-button" bindtap="clear">
<image src="/image/trash.png"></image>
</view>
</view>
</block> <block wx:if="{{hasRecord === true && playing === true}}">
<view class="page-body-time">
<text class="time-big">{{formatedPlayTime}}</text>
<text class="time-small">{{formatedRecordTime}}</text>
</view>
<view class="page-body-buttons">
<view class="page-body-button" bindtap="stopVoice">
<image src="/image/stop.png"></image>
</view>
<!-- <view class="page-body-button" bindtap="pauseVoice">
<image src="/image/pause.png"></image>
</view> -->
<view class="page-body-button" bindtap="clear">
<image src="/image/trash.png"></image>
</view>
</view>
</block>
</view>
</view> <template is="foot" />
</view>
d) .wxss
image {
width: 150rpx;
height: 150rpx;
} .page-body-wrapper {
justify-content: space-between;
flex-grow:;
margin-bottom: 300rpx;
}
.page-body-time {
display: flex;
flex-direction: column;
align-items: center;
}
.time-big {
font-size: 60rpx;
margin: 20rpx;
}
.time-small {
font-size: 30rpx;
} .page-body-buttons {
margin-top: 60rpx;
display: flex;
justify-content: space-around;
}
.page-body-button {
width: 250rpx;
text-align: center;
}
.button-stop-record {
width: 110rpx;
height: 110rpx;
border: 20rpx solid #fff;
background-color: #f55c23;
border-radius: 130rpx;
margin: 0 auto;
}
e)
3、background-audio 背景音频
a) .js
var app = getApp()
var util = require('../../../../util/util.js')
var dataUrl = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46'
Page({
onLoad: function () {
this._enableInterval() if (app.globalData.backgroundAudioPlaying) {
this.setData({
playing: true
})
}
},
data: {
playing: false,
playTime: 0,
formatedPlayTime: '00:00:00'
},
play: function (res) {
var that = this
wx.playBackgroundAudio({
dataUrl: dataUrl,
title: '此时此刻',
coverImgUrl: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
complete: function (res) {
that.setData({
playing: true
})
}
})
this._enableInterval()
app.globalData.backgroundAudioPlaying = true
},
seek: function (e) {
clearInterval(this.updateInterval)
var that = this
wx.seekBackgroundAudio({
position: e.detail.value,
complete: function () {
// 实际会延迟两秒左右才跳过去
setTimeout(function () {
that._enableInterval()
}, 2000)
}
})
},
pause: function () {
var that = this
wx.pauseBackgroundAudio({
dataUrl: dataUrl,
success: function () {
that.setData({
playing: false
})
}
})
app.globalData.backgroundAudioPlaying = false
},
stop: function () {
var that = this
wx.stopBackgroundAudio({
dataUrl: dataUrl,
success: function (res) {
that.setData({
playing: false,
playTime: 0,
formatedPlayTime: util.formatTime(0)
})
}
})
app.globalData.backgroundAudioPlaying = false
},
_enableInterval: function () {
var that = this
update()
this.updateInterval = setInterval(update, 500)
function update() {
wx.getBackgroundAudioPlayerState({
success: function (res) {
that.setData({
playTime: res.currentPosition,
formatedPlayTime: util.formatTime(res.currentPosition + 1)
})
}
})
}
},
onUnload: function () {
clearInterval(this.updateInterval)
}
})
b) .json
{
"navigationBarTitleText": "背景音乐"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'backgroundAudio'}}"/> <view class="page-section">
<view class="page-body-info">
<text class="time-big">{{formatedPlayTime}}</text>
<slider class="slider" min="0" max="269" step="1" value="{{playTime}}" bindchange="seek"></slider>
<view class="play-time">
<text>00:00</text>
<text>04:29</text>
</view>
</view>
<view class="page-body-text tc">注意:离开当前页面后背景音乐将保持播放,但退出小程序将停止</view>
<view class="page-body-buttons">
<block wx:if="{{playing === true}}">
<view class="page-body-button" bindtap="stop">
<image src="/image/stop.png"></image>
</view>
<view class="page-body-button" bindtap="pause">
<image src="/image/pause.png"></image>
</view>
</block>
<block wx:if="{{playing === false}}">
<view class="page-body-button"></view>
<view class="page-body-button" bindtap="play">
<image src="/image/play.png"></image>
</view>
</block>
<view class="page-body-button"></view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
image {
width: 150rpx;
height: 150rpx;
} .page-body-wrapper {
margin-top:;
}
.page-body-info {
padding-bottom: 50rpx;
}
.time-big {
font-size: 60rpx;
margin: 20rpx;
}
.slider {
width: 650rpx;
}
.play-time {
font-size: 28rpx;
width: 700rpx;
padding: 20rpx 0;
display: flex;
justify-content: space-between;
box-sizing: border-box;
}
.page-body-buttons {
display: flex;
justify-content: space-around;
margin-top: 100rpx;
}
.page-body-button {
width: 250rpx;
text-align: center;
}
e)
4、file 文件
a) .js
Page({
onLoad: function () {
this.setData({
savedFilePath: wx.getStorageSync('savedFilePath')
})
},
data: {
tempFilePath: '',
savedFilePath: '',
dialog: {
hidden: true
}
},
chooseImage: function () {
var that = this
wx.chooseImage({
count: 1,
success: function (res) {
that.setData({
tempFilePath: res.tempFilePaths[0]
})
}
})
},
saveFile: function () {
if (this.data.tempFilePath.length > 0) {
var that = this
wx.saveFile({
tempFilePath: this.data.tempFilePath,
success: function (res) {
that.setData({
savedFilePath: res.savedFilePath
})
wx.setStorageSync('savedFilePath', res.savedFilePath)
that.setData({
dialog: {
title: '保存成功',
content: '下次进入应用时,此文件仍可用',
hidden: false
}
})
},
fail: function (res) {
that.setData({
dialog: {
title: '保存失败',
content: '应该是有 bug 吧',
hidden: false
}
})
}
})
}
},
clear: function () {
wx.setStorageSync('savedFilePath', '')
this.setData({
tempFilePath: '',
savedFilePath: ''
})
},
confirm: function () {
this.setData({
'dialog.hidden': true
})
}
})
b) .json
{
"navigationBarTitleText": "文件"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'saveFile'}}"/> <view class="page-body">
<view class="page-section">
<view class="page-body-info">
<block wx:if="{{tempFilePath != ''}}">
<image src="{{tempFilePath}}" class="image" mode="aspectFit"></image>
</block>
<block wx:if="{{tempFilePath === '' && savedFilePath != ''}}">
<image src="{{savedFilePath}}" class="image" mode="aspectFit"></image>
</block>
<block wx:if="{{tempFilePath === '' && savedFilePath === ''}}">
<view class="image-plus image-plus-nb" bindtap="chooseImage">
<view class="image-plus-horizontal"></view>
<view class="image-plus-vertical"></view>
</view>
<view class="image-plus-text">请选择文件</view>
</block>
</view>
<view class="btn-area">
<button type="primary" bindtap="saveFile">保存文件</button>
<button bindtap="clear">删除文件</button>
</view>
</view>
</view> <modal title="{{dialog.title}}" hidden="{{dialog.hidden}}" no-cancel bindconfirm="confirm">{{dialog.content}}</modal> <template is="foot" />
</view>
d) .wxss
.image {
width: 100%;
height: 360rpx;
}
.page-body-info {
display: flex;
box-sizing: border-box;
padding: 30rpx;
height: 420rpx;
border-top: 1rpx solid #D9D9D9;
border-bottom: 1rpx solid #D9D9D9;
align-items: center;
justify-content: center;
}
e)
5、vedio 视频
a) .js
var sourceType = [ ['camera'], ['album'], ['camera', 'album'] ]
var camera = [ ['front'], ['back'], ['front', 'back'] ]
var duration = Array.apply(null, {length: 60}).map(function (n, i) {
return i + 1
}) Page({
data: {
sourceTypeIndex: 2,
sourceType: ['拍摄', '相册', '拍摄或相册'], cameraIndex: 2,
camera: ['前置', '后置', '前置或后置'], durationIndex: 59,
duration: duration.map(function (t) { return t + '秒'}), src: ''
},
sourceTypeChange: function (e) {
this.setData({
sourceTypeIndex: e.detail.value
})
},
cameraChange: function (e) {
this.setData({
cameraIndex: e.detail.value
})
},
durationChange: function (e) {
this.setData({
durationIndex: e.detail.value
})
},
chooseVideo: function () {
var that = this
wx.chooseVideo({
sourceType: sourceType[this.data.sourceTypeIndex],
camera: camera[this.data.cameraIndex],
maxDuration: duration[this.data.durationIndex],
success: function (res) {
that.setData({
src: res.tempFilePath
})
}
})
}
})
b) .json
{
"navigationBarTitleText": "拍摄/选择视频"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'chooseVideo'}}"/> <view class="page-body">
<view class="page-section">
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">视频来源</view>
</view>
<view class="weui-cell__bd">
<picker range="{{sourceType}}" bindchange="sourceTypeChange" value="{{sourceTypeIndex}}">
<view class="weui-input">{{sourceType[sourceTypeIndex]}}</view>
</picker>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">摄像头</view>
</view>
<view class="weui-cell__bd">
<picker range="{{camera}}" bindchange="cameraChange" value="{{cameraIndex}}">
<view class="weui-input">{{camera[cameraIndex]}}</view>
</picker>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">拍摄长度</view>
</view>
<view class="weui-cell__bd">
<picker range="{{duration}}" bindchange="durationChange" value="{{durationIndex}}">
<view class="weui-input">{{duration[durationIndex]}}</view>
</picker>
</view>
</view>
</view> <view class="page-body-info">
<block wx:if="{{src === ''}}">
<view class="image-plus image-plus-nb" bindtap="chooseVideo">
<view class="image-plus-horizontal"></view>
<view class="image-plus-vertical"></view>
</view>
<view class="image-plus-text">添加视频</view>
</block>
<block wx:if="{{src != ''}}">
<video src="{{src}}" class="video"></video>
</block>
</view>
</view>
</view>
</view>
d) .wxss
@import "../../../common/lib/weui.wxss"; .page-body-info {
display: flex;
margin-top: 40rpx;
padding:;
height: 360rpx;
border-top: 1rpx solid #D9D9D9;
border-bottom: 1rpx solid #D9D9D9;
align-items: center;
justify-content: center;
}
e)
6、
7. location 位置返回顶部 |
1、get-location 获取当前位置
a) .js
var util = require('../../../../util/util.js')
var formatLocation = util.formatLocation Page({
data: {
hasLocation: false,
},
getLocation: function () {
var that = this
wx.getLocation({
success: function (res) {
console.log(res)
that.setData({
hasLocation: true,
location: formatLocation(res.longitude, res.latitude)
})
}
})
},
clear: function () {
this.setData({
hasLocation: false
})
}
})
b) .json
{
"navigationBarTitleText": "获取位置"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'getLocation'}}"/> <view class="page-body">
<view class="page-section">
<view class="page-body-info">
<text class="page-body-text-small">当前位置经纬度</text>
<block wx:if="{{hasLocation === false}}">
<text class="page-body-text">未获取</text>
</block>
<block wx:if="{{hasLocation === true}}">
<view class="page-body-text-location">
<text>E: {{location.longitude[0]}}°{{location.longitude[1]}}′</text>
<text>N: {{location.latitude[0]}}°{{location.latitude[1]}}′</text>
</view>
</block>
</view>
<view class="btn-area">
<button type="primary" bindtap="getLocation">获取位置</button>
<button bindtap="clear">清空</button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.page-body-info {
height: 250rpx;
}
.page-body-text-small {
font-size: 24rpx;
color: #000;
margin-bottom: 100rpx;
}
.page-body-text-location {
display: flex;
font-size: 50rpx;
}
.page-body-text-location text {
margin: 10rpx;
}
e)
2、open-location 使用原生地图查看位置
a) .js
Page({
openLocation: function (e) {
console.log(e)
var value = e.detail.value
console.log(value)
wx.openLocation({
longitude: Number(value.longitude),
latitude: Number(value.latitude),
name: value.name,
address: value.address
})
}
})
b) .json
{
"navigationBarTitleText": "查看位置"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'openLocation'}}"/> <view class="page-body">
<view class="page-section">
<form bindsubmit="openLocation">
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">经度</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="113.324520" name="longitude"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">纬度</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="23.099994" name="latitude"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">位置名称</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="T.I.T 创意园" name="name"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">详细位置</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" disabled="{{true}}" value="广州市海珠区新港中路397号" name="address"></input>
</view>
</view>
</view>
<view class="btn-area">
<button type="primary" formType="submit">查看位置</button>
</view>
</form>
</view>
</view> <template is="foot" />
</view>
d) .wxss
@import "../../../common/lib/weui.wxss";
e)
3、choose-location 使用原生地图选择位置
a) .js
var util = require('../../../../util/util.js')
var formatLocation = util.formatLocation Page({
data: {
hasLocation: false,
},
chooseLocation: function () {
var that = this
wx.chooseLocation({
success: function (res) {
console.log(res)
that.setData({
hasLocation: true,
location: formatLocation(res.longitude, res.latitude),
locationAddress: res.address
})
}
})
},
clear: function () {
this.setData({
hasLocation: false
})
}
})
b) .json
{
"navigationBarTitleText": "使用原生地图选择位置"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'chooseLocation'}}"/> <view class="page-body">
<view class="page-section">
<view class="page-body-info">
<text class="page-body-text-small">当前位置信息</text>
<block wx:if="{{hasLocation === false}}">
<text class="page-body-text">未选择位置</text>
</block>
<block wx:if="{{hasLocation === true}}">
<text class="page-body-text">{{locationAddress}}</text>
<view class="page-body-text-location">
<text>E: {{location.longitude[0]}}°{{location.longitude[1]}}′</text>
<text>N: {{location.latitude[0]}}°{{location.latitude[1]}}′</text>
</view>
</block>
</view>
<view class="btn-area">
<button type="primary" bindtap="chooseLocation">选择位置</button>
<button bindtap="clear">清空</button>
</view>
</view>
</view> <template is="foot" />
</view>
d) .wxss
.page-body-info{
padding-bottom:;
height: 440rpx;
}
e)
4、
8. storage 数据返回顶部 |
1、storage 数据
a) .js
Page({
data: {
key: '',
data: '',
dialog: {
title: '',
content: '',
hidden: true
}
},
keyChange: function (e) {
this.data.key = e.detail.value
},
dataChange: function (e) {
this.data.data = e.detail.value
},
getStorage: function () {
var key = this.data.key,
data = this.data.data
var storageData if (key.length === 0) {
this.setData({
key: key,
data: data,
'dialog.hidden': false,
'dialog.title': '读取数据失败',
'dialog.content': 'key 不能为空'
})
} else {
storageData = wx.getStorageSync(key)
if (storageData === "") {
this.setData({
key: key,
data: data,
'dialog.hidden': false,
'dialog.title': '读取数据失败',
'dialog.content': '找不到 key 对应的数据'
})
} else {
this.setData({
key: key,
data: data,
'dialog.hidden': false,
'dialog.title': '读取数据成功',
'dialog.content': "data: '"+ storageData + "'"
})
}
}
},
setStorage: function () {
var key = this.data.key
var data = this.data.data
if (key.length === 0) {
this.setData({
key: key,
data: data,
'dialog.hidden': false,
'dialog.title': '保存数据失败',
'dialog.content': 'key 不能为空'
})
} else {
wx.setStorageSync(key, data)
this.setData({
key: key,
data: data,
'dialog.hidden': false,
'dialog.title': '存储数据成功'
})
}
},
clearStorage: function () {
wx.clearStorageSync()
this.setData({
key: '',
data: '',
'dialog.hidden': false,
'dialog.title': '清除数据成功',
'dialog.content': ''
})
},
confirm: function () {
this.setData({
'dialog.hidden': true,
'dialog.title': '',
'dialog.content': ''
})
}
})
b) .json
{
"navigationBarTitleText": "数据存储"
}
c) .wxml
<import src="../../../common/head.wxml" />
<import src="../../../common/foot.wxml" /> <view class="container">
<template is="head" data="{{title: 'get/set/clearStorage'}}"/> <view class="page-body">
<view class="page-section">
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">key</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" placeholder="请输入key" name="key" value="{{key}}" bindinput="keyChange"></input>
</view>
</view>
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">value</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" type="text" placeholder="请输入value" name="data" value="{{data}}" bindinput="dataChange"></input>
</view>
</view>
</view>
<view class="btn-area">
<button type="primary" bindtap="setStorage">存储数据</button>
<button bindtap="getStorage">读取数据</button>
<button bindtap="clearStorage">清理数据</button>
</view>
</view>
</view> <modal title="{{dialog.title}}" hidden="{{dialog.hidden}}" no-cancel bindconfirm="confirm">{{dialog.content}}</modal> <template is="foot" />
</view>
d) .wxss
@import "../../../common/lib/weui.wxss";
e)
2、
9.返回顶部 |
10.返回顶部 |
0、
1、
11.返回顶部 |
作者:ylbtech 出处:http://ylbtech.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |