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

26次阅读

共计 1256 个字符,预计需要花费 4 分钟才能阅读完成。

小程序文档上说

目前支持的选择器有:

选择器 样例 样例描述
.class .intro 选择所有拥有 class=”intro” 的组件
#id #firstname 选择拥有 id=”firstname” 的组件
element view 选择所有 view 组件
element, element view, checkbox 选择所有文档的 view 组件和所有的 checkbox 组件
::after view::after 在 view 组件后边插入内容
::before view::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]

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

正文完
 0