小程序模板网

微信小程序中多个button/view组件中进行切换时改变样式

发布时间:2017-12-25 11:37 所属栏目:小程序开发教程

微信小程序 | 多个按钮或VIEW,点击改变状态 简易的实现方法实现效果:背景图片:.wxml文件view plaincopyviewclass="chose-txt"data-price="{{item.price}}"data-id="{{index}}"bindtap="choseTxtColor"style="{{in ...

 
 
 

1、微信小程序 | 多个按钮或VIEW,点击改变状态 简易的实现方法

.wxml文件

 

		
  1. [html] view plain copy
  2. <view class="chose-txt" data-price="{{item.price}}" data-id="{{index}}" bindtap="choseTxtColor" style="{{index == id?'background:url(../resource/button/on_chose.png) right no-repeat; border:1rpx solid #e8580c; color: #e8580c':'baciground:url();border:1rpx solid gainsboro;color:gray'}}">
  3. <text class="chose-p" >{{item.name}}</text>
  4. <text class="chose-p" >{{item.price}}元</text>
  5. </view>
  6. </block>

样式都在这个文件中写了,CSS只是控制布局

.wxss文件

 

		
  1. [html] view plain copy
  2. .chose-txt{
  3. border-radius: 6px; font-size: 26rpx; height: 40px; width: 27.5%; margin: 5px; float: left;padding-top: 5px;
  4. }
  5. .chose-p{
  6. line-height: 18px; width: 100%; height:20px; text-align: center; float: left;
  7. }

.js页面

 

		
  1. [javascript] view plain copy
  2. var id ;
  3. page{
  4. array: [{ name: '单拍', price: '198'}, { name: '亲子套餐', price: '398' }, { name: '活动套餐', price: '598' }, { name: '女王套餐', price: '1198' } ],
  5. id:0, //进入页面时,默认选择第0个,如果不需要默认选中,注释掉就可以了
  6. },
  7. choseTxtColor:function(e){
  8. var id = e.currentTarget.dataset.id; //获取自定义的ID值
  9. this.setData({
  10. id:id
  11. })
  12. },
  13. }
  14. }

好了,到这里已经设置完成了,亲测可用。

 

2、微信小程序中多个button/view组件中进行切换时改变样式

在小程序项目中遇到一个问题:数据分成四五个小组,然后要进行小组切换,切换的同时把button的样式也要改变,以前Dom操作的时候特别简单,

现在在小程序中竟不知从何下手,后面参照了上面这边博文,功能也能够实现了,下面做下记录:

wxml代码:

 

		
  1. 1 <view wx:for="{{Object}}" wx:key="Object" wx:for-index="key" wx:for-item="value">
  2. 2 <view class="flex-item">
  3. 3 <button bindtap="changeGroup" data-groupid="{{value.id}}" data-id="{{key}} type="{{key == id ? 'primary' : 'default'}}"> {{value.name}}
  4. 4
  5. 5

css代码:

 

		
  1. 1 .flex-item button {
  2. 2 height: 32px;
  3. 3 box-sizing: border-box;
  4. 4 text-align: center;
  5. 5 margin: 10px 0 0 0;
  6. 6 min-width: 50px;
  7. 7 font-size: 16px;
  8. 8 line-height: 32px;
  9. 9 }

js代码:

 

		
  1. 1 data:{
  2. 2 id:''
  3. 3 }
 

		
  1. 1 changeGroup: function(event){
  2. 2 var id = event.currentTarget.dataset.id;
  3. 3 .....
  4. 4 this.setData({
  5. 5 id: id
  6. 6 });
  7. 7 }

结果:

默认为“全部”:



易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/18239.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询