微信小程式:多個button/view元件行切換時改變樣式
阿新 • • 發佈:2019-01-03
微信小程式中多個button/view,點選後改變狀態或樣式,並拿到對應引數值。該類似需求情境適用:選擇購物車的尺寸或是型號(不可選、可單選)、選擇套餐(單選)、選擇分組(單選)等等
按照需求佈局,根據陣列list迴圈,通過if語句條件渲染,展示對應樣式,其中view可換成button。
<view class="container">
<block wx:for="{{list}}" wx:key="{{index}}">
<!-- <view class="flag-item"> {{item.title}} </view> -->
<view wx:if="{{item.stock <= 0}}" class="flag-item0" bindtap="clickedBtn" data-id="{{index}}" > {{item.title}} </view>
<view wx:elif="{{item.stock > 0}}" class="{{index == current_tag?'flag-item2':'flag-item1'}}" bindtap="clickedAction" data-id="{{index}}"> {{item.title }} </view>
</block>
</view>
在wxss檔案寫css樣式
.container {
background-color: #fff;
width: 100%;
overflow: hidden;
}
.flag-item0 {
margin: 20rpx 2% 20rpx 2%;
width: 20%;
border: 1px solid gainsboro;
float: left;
text-align: center;
line-height: 40px;
color: gainsboro;
}
.flag-item1 {
margin: 20rpx 2% 20rpx 2%;
width: 20%;
border: 1px solid #000;
float: left;
text-align: center;
line-height: 40px;
}
.flag-item2 {
background-color: red;
margin: 20rpx 2% 20rpx 2%;
width: 20%;
border: 1px solid red;
float: left;
text-align: center;
line-height: 40px;
}
js檔案中寫對應的資料和邏輯
var networking = require('../../utils/networking.js');
var util = require('../../utils/util.js');
Page({
/**
* 頁面的初始資料
*/
data: {
// 資料列表
list:[
{
id:0,
title:"36",
stock:10
},
{
id: 1,
title: "37",
stock: 0
},
{
id: 2,
title: "38",
stock: 0
},
{
id: 3,
title: "39",
stock: 10
},
{
id: 4,
title: "40",
stock: 6
},
{
id: 5,
title: "41",
stock: 10
},
{
id: 6,
title: "42",
stock: 10
},
{
id: 7,
title: "43",
stock: 10
},
{
id: 8,
title: "44",
stock: 0
},
],
// 當前選中的號碼
current_tag:null,
},
/**
* 生命週期函式--監聽頁面載入
*/
onLoad: function (options) {
},
/**
* 生命週期函式--監聽頁面初次渲染完成
*/
onReady: function () {
},
/**
* 生命週期函式--監聽頁面顯示
*/
onShow: function () {
},
/**
* 生命週期函式--監聽頁面隱藏
*/
onHide: function () {
},
/**
* 生命週期函式--監聽頁面解除安裝
*/
onUnload: function () {
},
/**
* 頁面相關事件處理函式--監聽使用者下拉動作
*/
onPullDownRefresh: function () {
},
/**
* 頁面上拉觸底事件的處理函式
*/
onReachBottom: function () {
},
/**
* 使用者點選右上角分享
*/
onShareAppMessage: function () {
},
/**
* 庫存為0,不可選
*/
clickedBtn: function (responseObject) {
util.progressTips("補貨中,請耐心等待")
let that = this;
var id = responseObject.currentTarget.dataset.id; //獲取自定義的ID值
console.log("current_tag", id)
this.setData({
current_tag: id,
})
},
/**
* 庫存大於0,可選,選中變色
*/
clickedAction: function (responseObject){
let that = this;
var id = responseObject.currentTarget.dataset.id; //獲取自定義的ID值
console.log("current_tag", id)
this.setData({
current_tag: id,
})
}
})
可以檢視我的簡書,具體實現程式碼可以參考我的GitHub switch檔案中的程式碼。其中實現了兩種方式載入,一種是下拉重新整理和上拉載入結合,一種是單獨的上拉載入