uniapp线上商城随机寻宝

公司需加粗样式求:整个项目切换页面随机几率出现寻宝图标并点击获取积分。

思路:1.全局监听进入页面触发寻宝函数 2.获取屏幕宽高并且随机定位寻宝icon 3.触发背景音乐并且调用寻宝接获取积分。

本来想的好好的写在APP.Vue里面,但是里面三个函数都不提供页面监听。呜呜呜 在这里插入图片描述
那我只能自己封装一个函数然后在页面的onShow里调用了,虽然很麻烦但是没办法

首先我用uni提供的getSystemInfo获取了手机屏幕的宽高,并且存在缓存里。

//获取屏幕宽高
uni.getSystemInfo({
	success: (res) => {
		// console.log(res)
		uni.setStorageSync('windowWidth', res.windowWidth)
		uni.setStorageSync('windowHeight', res.windowHeight)
	}
})

然后写了个全局函数处理了一下这个随机出现的寻宝(返回一个view同理)

/**
 * 获取屏幕宽高并20%几率显示寻宝icon
 */
function showTreasureHunt() {
	let windowWidth = uni.getStorageSync('windowWidth')
	let windowHeight = uni.getStorageSync('windowHeight')
	console.log(windowWidth, windowHeight)

	//获取1-100的随机数
	let num = Math.floor(Math.random() * (1 - 100) + 100);
	if (num > 80) { //百分之20几率出现
		let widthNum = Math.floor(Math.random() * (1 - windowWidth) + windowWidth); //随机出现在屏幕宽之内
		let HeightNum = Math.floor(Math.random() * (1 - windowHeight) + windowHeight); //随机出现在屏幕高之内

		//减掉底部导航栏50px高度否则被覆盖
		let middle = windowHeight - 150
		if (HeightNum > middle) {
			HeightNum = HeightNum - (HeightNum - middle - 20)
		}
		//减掉右边距增加左边距
		widthNum = widthNum - 50
		if (widthNum < 0) {
			widthNum += 100
		}

		let xunbaoStyle =
			`width: 100rpx;height: 100rpx;position: fixed;top:${HeightNum}px;left:${widthNum}px;z-index: 99;`
		return xunbaoStyle
	}
}

这时候只需要在页面的onShow上调用一下

this.xunbaoStyle = this.$showTreasureHunt()

获取到这个样式直接放到模版上去

// 寻宝按钮
<view :style="xunbaoStyle">
	<image style="width: 100%;height: 100%;" src="https://image.pinhuie.com/storage/public/image/20210308154105609102.png"
	@click="clickXunbao"></image>
</view>

在这里插入图片描述
这样他就就会随机出现在页面的某个地方了qaq,接下来就是点击这个图片进行寻宝 我封装了一个函数直调用

// An highlighted block
/**
 * 点击寻宝
 */
async function clickXunbao() {
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	innerAudioContext.src = 'https://www.juniuzu.com/saqian.mp3';
	innerAudioContext.onError((res) => {
		//如果音频没有正常播放
		console.log(res.errCode);
	})
	return new Promise(resolve => {
		ajaxRequest({
			url: 'treasurehunt',
			showLoading: true,
			options: {
				method: 'get'
			},
			data: {},
			success: (result) => {
				resolve(result)
			}
		})
	}).catch((e) => {});
}

这里音频我没处理,因为我这个声音就一小段就放完了不需要关闭报错也不会,通过这个接口然后返回一个获取到的积分给页面然后渲染一下就可以了。

//寻宝
clickXunbao() {
	this.$clickXunbao().then(res => {
		this.point = res.point
		this.$refs.xunbaoPopupok.open()
		this.xunbaoStyle = 'overflow: hidden;'
	})
}

在这里插入图片描述
这样已经大功告成了!!!如果有更好的方法希望大家不吝赐教 谢谢。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值