欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【微信小程序】实现开关灯

程序员文章站 2024-03-20 20:13:10
...

【微信小程序】实现开关灯
light.wxml

<!--pages/light/light.wxml-->
<view wx:for="{{cons}}" class="light">
  <image
src ="{{item.src}}"
mode="aspectFill"
bindtap = "changeColor"
data-name = "{{index}}"> 
</image>
<h4>
{{item.isOn}}
</h4>
</view>

light.wxss

/* pages/light/light.wxss */
.light image{
  width: 100rpx;
  height: 100rpx;
  margin-right: 50rpx;
  display: block;
}
.light{
  float: left;
}
h4 {
  padding-left:15rpx;
}

light.js

  • 重要:三目运算符
// pages/light/light.js
Page({
  
  /**
   * Page initial data
   */
  data: {
    // imgUrl: "../../imgs/bulb.png"
    cons: [
      {isOn: "off", src:"../../imgs/bulb.png"},
      {isOn: "off", src:"../../imgs/bulb.png"},
      {isOn: "off", src:"../../imgs/bulb.png"}
    ]

  },

  changeColor(e){
    // 获取索引值
    // console.log(e.currentTarget.dataset.name)
    let index = e.currentTarget.dataset.name

    this.data.cons[index].src = this.data.cons[index].src == "../../imgs/bulb.png"?"../../imgs/bulbSel.png":"../../imgs/bulb.png"

    this.data.cons[index].isOn = this.data.cons[index].isOn == "on"?"off":"on"

    this.setData({
      cons: this.data.cons
    })
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function (options) {

  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function () {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function () {

  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function () {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function () {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function () {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom: function () {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage: function () {

  }
})