目录
微信小程序开发问题汇总
样式如何使用变量
video遮罩问题
弹幕自动上推信息流
软键盘问题
websocket使用
weapp.socket.io
小程序当中的使用
首页 微信小程序 小程序开发 汇总微信小程序开发问题

汇总微信小程序开发问题

Dec 04, 2020 pm 04:44 PM
微信小程序

小程序开发教程栏目介绍微信小程序开发的一些问题

汇总微信小程序开发问题

推荐(免费):小程序开发教程

微信小程序开发问题汇总

  • 样式如何使用变量
  • video遮罩问题
  • 弹幕自动上推信息流
  • 软键盘问题
  • websocket使用
    • weapp.socket.io
    • 小程序当中的使用

小程序开发告一段落,总结一下这段时间小程序开发遇到的问题及解决方案,react冲冲冲!!!

样式如何使用变量

在wxss中,定义变量:width:var(–width–);

在js中,定义变量:viewWidth,并给这个变量赋予想要的值

在wxml中,使用wxss中的变量和js中的变量:style="–width–: {{ viewWidth }}px"

video遮罩问题

在实现直播的功能时,我们需要弹出红包等遮盖video的处理,此时会发现,使用z-index属性在小程序中是无效的,微信开发者文档提供了cover-view,cover-imge等控件实现遮罩的功能。
这里值得注意的是cover-view中的background-image属性是无效的,所以我们要安放背景图时需要使用到cover-image,并且将它的position设置为absolute, top为0, left也为0即可。

弹幕自动上推信息流

在这里插入图片描述
首先是将这个scroll的高度定死,让scroll自动滑动到某个item的位置:

    <scroll-view class="danmu-list" scroll-y="true" scroll-into-view="{{&#39;item_&#39; + danmulist.length}}" style="height: {{windowHeight - 890}}rpx">
        <view id="{{&#39;item_&#39; + (index + 1)}}" wx:for="{{danmulist}}" class="{{item.nickName == username ? &#39;danmu-item owner&#39; : &#39;danmu-item&#39;}}" wx:key="this">
          <view class="nickname">{{item.nickName}}:</view>
          <view class="content {{ item.system ? &#39;system&#39; : &#39;&#39; }}" style="color: {{ item.system ? &#39;#71f474&#39; : (item.color || &#39;#fff&#39;)}}">{{item.content}}</view>
        </view>
    </scroll-view>
登录后复制

为scroll添加样式:

.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的属性,并且为每个item添加一个id即可。
那么有没有纯css的实现呢?当然。
我们将item都放在一个盒子中,让盒子的相对于list底部对齐,overflow则进行scroll,这样同样能实现现在的效果。

软键盘问题

此次开发,需要实现一个输入框点击,软键盘弹起,选择颜色功能。我们看下效果图:
在这里插入图片描述
那么考虑几个问题:
1、选择颜色时键盘失去焦点会缩起
微信小程序提供了一个hold-keyboard属性
在这里插入图片描述
我在input 中设定了hold-keyboard="true"
2、软键盘弹出时会自动把页面上推,但是我们仅仅想要软键盘把input框上推而不是整个页面。
分析一下这个问题,首先是考虑纯css解决方案,把页面设为fixed,然而不起作用;接下来考虑页面弹起时减去软键盘的高度让它恢复到原位,这会带来两个问题:1)软键盘弹起后才能获取软键盘高度,这样一来页面的下落会产生严重的滞后;2)同样的不起作用
这个问题最终的解决方案是这样的:
首先查看官方文档,微信小程序提供了一个adjust-position属性
在这里插入图片描述
设定adjust-position=“false",此时的确不会进行页面的上推了,但是我们需要的input框上推如何实现?
我们可以在input的方法参数e.detail.height中拿到软键盘的高度,设定input的高度为e.detail.height的高度即可。
最终代码:

 <cover-view wx:if="{{inputParam.colorShow}}" class="color-check" style="bottom: {{inputParam.bottom + (windowWidth / 750 * 90)}}px">
   <cover-image class="color-background" src="{{assets}}/images/live-index-danmu-send-color-check.png"></cover-image>
   <cover-view class="color-list">
     <cover-view wx:for="{{colorStatusList}}" wx:key="this" catchtap="checkColor" data-index="{{index}}" class="{{item.checked == 0 ? &#39;color-icon&#39; : &#39;color-icon with-border&#39;}}" style="background-color: {{item.color}}"></cover-view>
   </cover-view>
 </cover-view>
 
 <view class="enterDanmu" style="bottom: {{inputParam.bottom}}px">
	  <input hold-keyboard="true" catchtap catchfocus="enterMessage" bindconfirm="loseColor" bindinput="getInputValue" placeholder="发个弹幕呗~"
	     placeholder-style="font-size: 26rpx; color: #09091b" style="color:{{fontcolor}};"
	     value="{{inputParam.inpuentertValue}}" focus="{{inputParam.focus}}" adjust-position="{{false}}"></input>
     <image catchtap="sendMessageOperation" class="danmu-btn" src="{{assets}}images/live-index-danmu-send.png"></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,
      })
    }

  }
登录后复制

至于说上面的catchtap则很好理解了,当我们要点击任意处导致失去焦点时,必定要在外层绑定bindtap事件,那么此处就需要使用catchtap阻止事件的冒泡。
值得一提的是,微信小程序也提供了一个wx.onKeyboardHeightChange(function callback)方法来监听键盘的高度变化,但是亲测这个方法并没有很好用,尝试了一下就弃之不用了。

websocket使用

我们都知道 HTTP 协议有一个缺陷:通信只能由客户端发起。那么在这种情况下,如果服务器有连续的状态变化,客户端要获知就非常麻烦。我们只能使用"轮询",最典型的应用场景就是聊天室了。
轮询的效率低,非常浪费资源。因此,工程师们一直在思考,有没有更好的方法。WebSocket 就是这样发明的。
那么如何在微信小程序中使用websocket呢?先来看看本次的需求:
在观看直播的过程当中,用户会进行聊天,服务器要将用户的弹幕信息推送到每个用户的手机端。

weapp.socket.io

weapp.socket.io是基于socket.io的微信程序环境中的客户端,以及socket.io-client浏览器版本的完整功能。
安装方式:

npm i weapp.socket.io
登录后复制

简单使用的代码:

<template>
    <view class="content">
       <button type="primary" @click="send">发送消息</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培训栏目!

以上是汇总微信小程序开发问题的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

闲鱼微信小程序正式上线 闲鱼微信小程序正式上线 Feb 10, 2024 pm 10:39 PM

闲鱼官方微信小程序悄然上线,在小程序中可以发布闲置与买家/卖家私信交流、查看个人资料及订单、搜索物品等,有用好奇闲鱼微信小程序叫什么,现在快来看一下。闲鱼微信小程序叫什么答案:闲鱼,闲置交易二手买卖估价回收。1、在小程序中可以发布闲置、与买家/卖家私信交流、查看个人资料及订单、搜索指定物品等功能;2、在小程序的页面中有首页、附近、发闲置、消息、我的5项功能;3、想要使用的话必要要开通微信支付才可以购买;

微信小程序实现图片上传功能 微信小程序实现图片上传功能 Nov 21, 2023 am 09:08 AM

微信小程序实现图片上传功能随着移动互联网的发展,微信小程序已经成为了人们生活中不可或缺的一部分。微信小程序不仅提供了丰富的应用场景,还支持开发者自定义功能,其中包括图片上传功能。本文将介绍如何在微信小程序中实现图片上传功能,并提供具体的代码示例。一、前期准备工作在开始编写代码之前,我们需要先下载并安装微信开发者工具,并注册成为微信开发者。同时,还需要了解微信

实现微信小程序中的下拉菜单效果 实现微信小程序中的下拉菜单效果 Nov 21, 2023 pm 03:03 PM

实现微信小程序中的下拉菜单效果,需要具体代码示例随着移动互联网的普及,微信小程序成为了互联网开发的重要一环,越来越多的人开始关注和使用微信小程序。微信小程序的开发相比传统的APP开发更加简便快捷,但也需要掌握一定的开发技巧。在微信小程序的开发中,下拉菜单是一个常见的UI组件,实现了更好的用户操作体验。本文将详细介绍如何在微信小程序中实现下拉菜单效果,并提供具

使用微信小程序实现轮播图切换效果 使用微信小程序实现轮播图切换效果 Nov 21, 2023 pm 05:59 PM

使用微信小程序实现轮播图切换效果微信小程序是一种轻量级的应用程序,具有简单、高效的开发和使用特点。在微信小程序中,实现轮播图切换效果是常见的需求。本文将介绍如何使用微信小程序实现轮播图切换效果,并给出具体的代码示例。首先,在微信小程序的页面文件中,添加一个轮播图组件。例如,可以使用&lt;swiper&gt;标签来实现轮播图的切换效果。在该组件中,可以通过b

实现微信小程序中的图片滤镜效果 实现微信小程序中的图片滤镜效果 Nov 21, 2023 pm 06:22 PM

实现微信小程序中的图片滤镜效果随着社交媒体应用的流行,人们越来越喜欢在照片中应用滤镜效果,以增强照片的艺术效果和吸引力。在微信小程序中也可以实现图片滤镜效果,为用户提供更多有趣和创造性的照片编辑功能。本文将介绍如何在微信小程序中实现图片滤镜效果,并提供具体的代码示例。首先,我们需要在微信小程序中使用canvas组件来加载和编辑图片。canvas组件可以在页面

闲鱼微信小程序叫什么 闲鱼微信小程序叫什么 Feb 27, 2024 pm 01:11 PM

闲鱼官方微信小程序已经悄然上线,它为用户提供了一个便捷的平台,让你可以轻松地发布和交易闲置物品。在小程序中,你可以与买家或卖家进行私信交流,查看个人资料和订单,以及搜索你想要的物品。那么闲鱼在微信小程序中究竟叫什么呢,这篇教程攻略将为您详细介绍,想要了解的用户们快来跟着本文继续阅读吧!闲鱼微信小程序叫什么答案:闲鱼,闲置交易二手买卖估价回收。1、在小程序中可以发布闲置、与买家/卖家私信交流、查看个人资料及订单、搜索指定物品等功能;2、在小程序的页面中有首页、附近、发闲置、消息、我的5项功能;3、

如何使用PHP开发微信小程序的二手交易功能? 如何使用PHP开发微信小程序的二手交易功能? Oct 27, 2023 pm 05:15 PM

如何使用PHP开发微信小程序的二手交易功能?微信小程序作为一种热门的移动应用开发平台,被越来越多的开发者所使用。在微信小程序中,二手交易是一种常见的功能需求。本文将介绍如何使用PHP开发微信小程序的二手交易功能,并提供具体的代码示例。一、准备工作在开始开发前,需要先确保已具备以下条件:微信小程序的开发环境已搭建完成,包括注册小程序的AppID,并在小程序后台

实现微信小程序中的图片旋转效果 实现微信小程序中的图片旋转效果 Nov 21, 2023 am 08:26 AM

实现微信小程序中的图片旋转效果,需要具体代码示例微信小程序是一种轻量级的应用程序,为用户提供了丰富的功能和良好的用户体验。在小程序中,开发者可以利用各种组件和API来实现各种效果。其中,图片旋转效果是一种常见的动画效果,可以为小程序增添趣味性和视觉效果。在微信小程序中实现图片旋转效果,需要使用小程序提供的动画API。下面是一个具体的代码示例,展示了如何在小程

See all articles