Summary of WeChat applet development issues
## Mini Program Development Tutorial This column introduces some issues in WeChat Mini Program development
Mini Program Development Tutorial
Summary of WeChat Mini Program Development Issues- How to use variables in styles
- Video masking problem
- Barrage automatically pushes information flow
- Soft keyboard problem
- Websocket use
- weapp.socket.io
- Usage in mini programs
{ viewWidth }}px"
Video masking problemWhen implementing the live broadcast function, we need to pop up red envelopes and other processes to cover the video. At this time, we will find that using the z-index attribute is invalid in the mini program. WeChat developer documentation provides Cover-view, cover-imge and other controls are used to implement the mask function. It is worth noting here that the background-image attribute in cover-view is invalid, so when we want to place the background image, we need to use cover-image, and set its position to absolute, top to 0, and left to 0. It can be 0.
The first is to set the height of the scroll and let the scroll automatically slide to the position of a certain item:
<scroll-view> <view> <view>{{item.nickName}}:</view> <view>{{item.content}}</view> </view> </scroll-view>
.danmu-list { width: 750rpx; height: 290rpx; position: relative; padding-top: 27rpx;}.danmu-item { padding: 0 27rpx;}.danmu-item .nickname { color: #cdd5ff; font-size: 26rpx; display: inline-block;}.danmu-item.owner .nickname { color: #ffab00;}.danmu-item .content { color: #ffffff; font-size: 26rpx; display: inline-block;}
scroll-into-view , and just add an id to each item.
So is there any pure css implementation? certainly.
We put all the items in a box, align the box with the bottom of the list, and scroll the overflow, so that the current effect can be achieved.
Then consider a few issues:
1. When selecting a color, the keyboard will shrink when it loses focus
The WeChat applet provides a
hold-keyboard Attributes
I set
hold-keyboard="true" in the input. 2. The soft keyboard will automatically push the page up when it pops up, but We just want the soft keyboard to push the input box up instead of the entire page.
Analyze this problem. First, consider a pure CSS solution, setting the page to fixed, but it does not work. Next, consider subtracting the height of the soft keyboard when the page pops up to restore it to its original position. This will bring There are two problems: 1) The height of the soft keyboard can only be obtained after the soft keyboard bounces up, which will cause serious lag when the page falls; 2) The same does not work
The final solution to this problem is as follows:
First check the official documentation. The WeChat applet provides an
adjust-position attribute
setting
adjust-position="false", this It is true that the page will not be pushed up at this time, but how to push up the input box we need?
We can get the height of the soft keyboard in the input method parameter e.detail.height, and set the height of the input to the height of e.detail.height.
Final code:
<cover-view> <cover-image></cover-image> <cover-view> <cover-view></cover-view> </cover-view> </cover-view> <view> <input> <image></image> </view>
checkColor(e) { let colorStatusList = this.data.colorStatusList; let index = e.currentTarget.dataset.index; let foncolor = colorStatusList[index].color; let inputParam = this.data.inputParam inputParam.focus = true if (colorStatusList[index].checked == true) { colorStatusList[index].checked = false foncolor = '#09091b' } else { for (let colorIndex in colorStatusList) { colorStatusList[colorIndex].checked = false } colorStatusList[index].checked = true } this.setData({ colorStatusList: colorStatusList, fontcolor: foncolor, inputParam: inputParam }) }, getInputValue(e) { let inputParam = this.data.inputParam; inputParam.inputValue = e.detail.value; this.setData({ inputParam: inputParam }) }, enterMessage(e) { let inputParam = this.data.inputParam; inputParam.colorShow = true, inputParam.focus = true, inputParam.bottom = e.detail.height this.setData({ inputParam: inputParam, }) }, loseColor() { let inputParam = this.data.inputParam; inputParam.colorShow = false; inputParam.focus = false; inputParam.bottom = 0; this.setData({ inputParam: inputParam, }) }, sendMessageOperation(e) { let inputParam = this.data.inputParam; if (inputParam.inputValue != '') { this.socket.emit('message', inputParam.inputValue, this.data.fontcolor); app.api.send_message(this.data.liveId, this.data.fontcolor, inputParam.inputValue); inputParam.inputValue = ''; inputParam.colorShow = false inputParam.focus = false inputParam.bottom = 0 this.setData({ inputParam: inputParam, }) console.log("sendMessageOperation") } else { inputParam.inputValue = ''; inputParam.colorShow = false inputParam.focus = false this.setData({ inputParam: inputParam, }) } }
It is worth mentioning that the WeChat applet also provides a
wx.onKeyboardHeightChange(function callback) method to monitor the height changes of the keyboard. However, this method did not work well in personal testing. I tried it. Discarded immediately.
websocket使用
我们都知道 HTTP 协议有一个缺陷:通信只能由客户端发起。那么在这种情况下,如果服务器有连续的状态变化,客户端要获知就非常麻烦。我们只能使用"轮询",最典型的应用场景就是聊天室了。
轮询的效率低,非常浪费资源。因此,工程师们一直在思考,有没有更好的方法。WebSocket 就是这样发明的。
那么如何在微信小程序中使用websocket呢?先来看看本次的需求:
在观看直播的过程当中,用户会进行聊天,服务器要将用户的弹幕信息推送到每个用户的手机端。
weapp.socket.io
weapp.socket.io是基于socket.io的微信程序环境中的客户端,以及socket.io-client浏览器版本的完整功能。
安装方式:
npm i weapp.socket.io
简单使用的代码:
<template> <view> <button>发送消息</button> </view></template>
// 引入 weapp.socket.io.js import io from '@/util/weapp.socket.io.js';export default { data() { return {}; }, onLoad() { // 建立一个socket连接 const socket =(this.socket = io('https://socket-io-chat.now.sh/')); /** * 客户端socket.on()监听的事件: */ // 连接成功 socket.on('connect', () => { console.log('连接成功'); }); // 正在连接 socket.on('connecting', d => { console.log('正在连接', d); }); // 连接错误 socket.on('connect_error', d => { console.log('连接失败', d); }); // 连接超时 socket.on('connect_timeout', d => { console.log('连接超时', d); }); // 断开连接 socket.on('disconnect', reason => { console.log('断开连接', reason); }); // 重新连接 socket.on('reconnect', attemptNumber => { console.log('成功重连', attemptNumber); }); // 连接失败 socket.on('reconnect_failed', () => { console.log('重连失败'); }); // 尝试重新连接 socket.on('reconnect_attempt', () => { console.log('尝试重新重连'); }); // 错误发生,并且无法被其他事件类型所处理 socket.on('error', err => { console.log('错误发生,并且无法被其他事件类型所处理', err); }); // 加入聊天室 socket.on('login', d => { console.log(`您已加入聊天室,当前共有 ${d.numUsers} 人`); }); // 接受到新消息 socket.on('new message', d => { console.log('new message',d); }); // 有人加入聊天室 socket.on('user joined', d => { console.log(`${d.username} 来了,当前共有 ${d.numUsers} 人`); }); // 有人离开聊天室 socket.on('user left', d => { console.log(`${d.username} 离开了,当前共有 ${d.numUsers} 人`); }); }, methods: { send(){ // 发送消息 this.socket.emit('new message', '发送消息') } }};
小程序当中的使用
initWebSocket(live) { if(this.socket) { this.socket.disconnect(); this.socket = null; } if(live.step != '直播中') { return this.setData({ liveTipTime: live.start_time }); } const username = this.data.username; const timestamp = Math.floor(Date.now()/1000/60/10); const token = `gz.${timestamp}.${username}`; const socket = io( `${socketHost}/chat?id=${this.data.liveId}&token=${token}`); socket.on('connect', () => { this.setData({ socketError: '' }); console.log('connection created.') }); socket.on('join', user => { let { danmulist } = this.data; danmulist.push({ nickName: user, content: '加入了房间', system: true }); this.setData({ danmulist, onlineUserCount: this.data.onlineUserCount + 1 }); }); socket.on('message', msg => { let { danmulist } = this.data; danmulist.push({ nickName: msg.user, content: msg.content, color: msg.color || '#fff' }); this.videoContext.sendDanmu({ text: msg.content, color: msg.color || '#fff' }) this.setData({ danmulist }); console.log(msg) }); socket.on('alluser', users => { //console.log('alluser', users); this.setData({ onlineUserCount: users.length }); }); socket.on('logout', users => { console.log('alluser', users) this.setData({ onlineUserCount: this.data.onlineUserCount - 1 }); }); socket.on('getAlluser', ({ type, users }) => { console.log('getAlluser', type, users); if(this.data.isAdmin) { app.api.lottery_start(type, users).then(x=>{ if(!x.length) { return wx.showModal({ content: '当前已无符合条件的中奖候选名单,请稍后再试' }); } wx.showToast({ title: '抽奖成功' }); this.setData({ activeTab: 0 }); this.socket.emit('lotteryStart', type); this.lottery_result_summary(); }).catch(e=>{ wx.showModal({ title: '抽奖失败: '+e, showCancel: false }); }); } }); socket.on('setScore', score => { const liveIndex = this.data.swiperList.findIndex(x=>x.id == this.data.liveId); if(this.data.swiperList[liveIndex]) { this.setData({ [`swiperList[${liveIndex}].score`]: score }); } console.log('setScore', score) }); socket.on('lotteryStart', type => { console.log('lotteryStart', type) if(this.data.lotteryStatus == 1) { app.api.lottery_result(type).then(lotteryResult=>{ this.setData({ lotteryStatus: 2, lotteryResult, time2: 10 }); this.countdown(); }); } }); socket.on('setliveStep', step => { console.log('setliveStep', step) }); socket.on('error', e => { console.error('socket error', e); wx.showToast({ title: '连接弹幕服务失败', icon: 'none' }); this.setData({ socketError: e + '' }); }) this.socket = socket; this.setData({ liveTipTime: '' }); },
想了解更多编程学习,敬请关注php培训栏目!
The above is the detailed content of Summary of WeChat applet development issues. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to
