前几日,遇到一位同学咨询我,小程序页面的图文列表(使用wx:for渲染出来的)如何实现点赞某条的效果,特此写了这样一个简单的Demo,今天来分享给大家。 微信小程序渲染的列表信息数据很难从视图层去单独修改某一个列表渲染的数据样式。原因一是无法像WEB开发是直接操作DOM,另一方面部分小程序开发者不了解小程序VIEW层的渲染机制。细节点说明: 1、列表的数据来源于JS,因此在无法操作dom的情况下就只能修改数据(体现数据驱动模式)。 2、使用data-*来存储当前点击的项对应的点赞数量。 3、添加一个额外的hasChanged属性来记录该项是否已经点赞(如果允许一个用户不停点赞,可以取消该属性)。 直接贴代码了。 index.wxml [HTML] 纯文本查看 复制代码 
 index.wxss [CSS] 纯文本查看 复制代码 .container {  background: #fff;  height: 100%;  font-family: 'Miscrsoft YaHei'}.list {  background: #ddd;  position: relative;  padding: 10px 10px 10px 70px;  height: 50px;  margin-bottom: 10px;}.praise {  width: 50px;  height: 50px;  background: #999;  text-align: center;  line-height: 50px;  border-radius: 50%;  position: absolute;  left: 10px;  transition: 0.5s;  color: #fff;}.hover_praise, .changed {  transition: 0.5s;  background: #f5d;}.author {  display: block;  height: 20px;}.info {  height: 30px;  line-height: 30px;  font-size: 12px;}index.js [JavaScript] 纯文本查看 复制代码 const app = getApp()Page({  data: {  },  onLoad: function () {    this.list = [{      'author': 'xiongcf',      'info': 'just for example praise list item.',      'praise': 0,      'hasChange': false    },    {      'author': 'xiongcc',      'info': 'just for example praise list item.',      'praise': 133,      'hasChange': false    },    {      'author': 'xiongff',      'info': 'just for example praise list item.',      'praise': 0,      'hasChange': false    },    {      'author': 'xiongf',      'info': 'just for example praise list item.',      'praise': 8,      'hasChange': false    },    {      'author': 'xiongfc',      'info': 'just for example praise list item.',      'praise': 33,      'hasChange': false    }]    this.setData({      list: this.list    })  },  praiseThis: function (e) {    var index = e.currentTarget.dataset.curindex;    if (this.list[index]) {      var hasChange = this.list[index].hasChange;      if (hasChange !== undefined) {        var onum = this.list[index].praise;        if (hasChange) {          this.list[index].praise = (onum - 1);          this.list[index].hasChange = false;        } else {          this.list[index].praise = (onum + 1);          this.list[index].hasChange = true;        }        this.setData({          list: this.list        })      }    }  }})效果在附近视频里 praise.rar列表点赞.mp4 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!  |