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

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

小程序文档上说

目前支持的选择器有:

选择器样例样例描述
.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]


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_4729