微信小程序css选择器的使用

微信小程序 css 选择器的使用

在开发微信小程序时遇到了一个很特殊的情况,记录一下以防自己忘记。

微信小程序官方文档中很多地方都说明了小程序中是无法使用 css 的部分选择器的,例如:

https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/#%E5%88%9B%E5%BB%BA%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6

说明自定义组件中无法使用 ID 选择器、属性选择器和标签名选择器。

并且在教程中也说明了仅支持少部分的选择器:https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxss.html

如果使用错误则会在调试工具中显示警告:

1
Some selectors are not allowed in component wxss, including tag name selectors, ID selectors, and attribute selectors.

但在实际使用的过程中发现,在某些特殊情况下是可以使用的。

例如在使用 iconfont 的时候,使用 icomoon 生成的样式在页面中可以生效:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[class^="icomoon-"],
[class*=" icomoon-"] {
/* use !important to prevent issues with browser extensions that change fonts */
font-family: "#{$icomoon-font-family}" !important;
speak: never;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;

/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

经过多次测试之后发现以下规律:

  1. 当页面在主包中时,引用的组件中可以使用属性选择器
  2. 当页面不在主包中时,引用的组件中无法使用属性选择器
  3. 不论页面在主包还是分包中,页面中都可以直接使用属性选择器

也就是说只要是页面都可以使用属性选择器,但如果是组件,则要看引用他的页面是否在主包中,如果在主包中则可以使用。


微信小程序css选择器的使用
https://www.wobushi.top/2022/微信小程序css选择器的使用/
作者
Pride Su
发布于
2022年10月25日
许可协议