微信小程序文档没写支持, 但是实际支持的选择器有哪些?

1,983 阅读2分钟

小程序文档上说

目前支持的选择器有:

选择器样例样例描述
.class.intro选择所有拥有 class="intro" 的组件
#id#firstname选择拥有 id="firstname" 的组件
elementview选择所有 view 组件
element, elementview, checkbox选择所有文档的 view 组件和所有的 checkbox 组件
::afterview::after在 view 组件后边插入内容
::beforeview::before在 view 组件前边插入内容

在实践中我发现, 除了文档上说的几种选择器, 经过测试发现其实还有几种支持的选择器没有列举!

还支持哪些选择器?

后面讲解的例子都以此xml结构为基础:

<view class="parent">
    <text class="son son-1">大儿子</text>
    <text class="son son-2" space>二儿子</text>
    <text class="son son-3">三儿子</text>
</view>
<button type="primary">按钮</button>

"~"选择器

选择其后所有同级元素:

.parent text {
  display: block;
  font-size: 24px;
}
text.son-1 ~ text {
  color: #69c;
}

"+"选择器

选择其后紧邻同级元素:

.parent text {
  display: block;
  font-size: 24px;
}
text.son-1 + text {
  color: #69c;
}

xx:nth-child(n)

第n个xx表达式对应的元素

.parent>text {
  display: block;
  font-size: 24px;
}
.parent>text:nth-child(2) {
  color: #f10;
}

经过测试, 类似的还有 ::last-of-type(n), :nth-last-child(n), :nth-last-of-type(n), :first-of-type 也都好使.

[attribute]

拥有attribute属性的元素

button[type]{
    height: 200px;
}

经过测试, 类似的还有 :[attribute=value], [attribute~=value], [attribute|=value] 也都好使.

注: 由于微信支持的标签上的属性和html的并不一致, 有很多html支持的属性微信是不支持的, 如果不支持的属性是没有使用属性选择器的. 微信支持的标签

总结

列一下本文补充的选择器:

  • :nth-child(n)
  • :last-of-type(n)
  • :nth-last-child(n)
  • :nth-last-of-type(n)
  • :first-of-type
  • [attribute]
  • [attribute=value]
  • [attribute~=value]
  • [attribute|=value]

我也是刚开始学习微信小程序开发可能还有遗漏, 还请大家包涵以及指正,后续如有新的发现我也会补充到本文, 方便大家查阅, 感谢阅读.

前端微信群

有疑问可以加群, 群里有好多前端的小伙伴, 让我们共同学习成长吧!