小程序组件.active引用变量【已解决】

最近在开发小程序的个人组件,想封装一个button的小组件方便以后自己用.想做那种点下去,背景色会有个动画效果的那种

主要问题

众所周知,小程序的.wxss文件并不能直接,直接传入变量
那么我们如果要通过JS来修改CSS里面的值怎么办呢?

没错,在标签的style直接绑定变量,例如

	<view styel="backgroud-color:{{变量}}"></view>

那么有时候我们可能也需要要用到一些伪类元素,比如.hover,.acitve

然而这些伪劣元素,并不能在标签色style里面直接绑定变量,那怎么办呢

点击前↓
在这里插入图片描述
在这里插入图片描述
按着时↑

(PS:我还想要一个动态变化效果,由skyblue变成white)

就类似上面的效果,当我按住时,显示button的背景色和字体颜色边框颜色会发生改变

因为我是要做成组件的,当然希望这些背景色,和字体颜色的值能够传入,而不是写死


问题来了,怎么实现

我们利用小程序自带的一个点击事件touchstart和touchend

touchstart

当点击元素的时候触发

touchend

当被点击元素点击结束时触发

下面是实现的组件代码


button.js

Component({
  properties: {
    // 内容文字
    text: {
      value: "",
      type: String
    },
    // 传入背景色
    backgroundColor: {
      value: "",
      type: String
    },
    // 传入字体颜色
    color: {
      value: "",
      type: String
    },
  },
  data: {
    // 控制class的动态添加和减少
    show: false
  },
  methods: {
    // 点击触发函数
    touchStart() {
      const that = this;
      that.setData({
        show: true
      })
    },
    // 点击结束函数
    touchEnd() {
      this.setData({
        show: false
      })
    }
  }
})

button.wxml

<view class="button-contant" bindtouchstart="touchStart" bindtouchend="touchEnd" 
style=" box-shadow: 0rpx 0rpx 8rpx 1rpx {{backgroundColor}}; background:{{backgroundColor}}">
    <view class="cover" style="background:{{show?color:backgroundColor}};">
        <view style="color:{{show?backgroundColor:color}}">{{text}}</view>
    </view>
</view>

button.wxss

.button-contant {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
    overflow: hidden;
}

.cover {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    transition: background 0.1s;
}

view {
    box-sizing: border-box;
}

button.json

{
    "component": true
}

然后再其他地方引用

<view style="width:200rpx;height:80rpx;margin:30rpx;">
    <btn text="123132" backgroundColor="skyblue" color="#fff"></btn>
</view>

记得在需要使用组件的.json文件里面使用组件的路径哟

{
    "usingComponents": {
        "test": "组件路径"
    }
}

好啦然后问题就解决啦…小编接触小程序开发不久,如果有做的不好的地方希望大家能指出,最近也在造轮子,做自己的UI组件库…希望大家多多支持,附上我的github地址,传送门~~~~~开:

https://github.com/qq894617385/congUI

猜你喜欢

转载自blog.csdn.net/weixin_43285211/article/details/83861059