小程序/uniapp支持的css选择器一览

6次阅读

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

本次测试主要参考文档为 w3school CSS 选择器参考手册

(主要是安卓 /ios/ 微信小程序的 css 选择器兼容)
入坑 uniapp/ 小程序过程中看到 dcloud/ 微信对支持的 css 选择器的描述只有六个, 分别是.class,#id,element,element,element,:before,:after 但是看到 dcloud 给 uniapp 写的花里胡哨的 uni 的 ui 库, 还有各种花里胡哨的小程序, 并且 uniapp 还表明支持之前各种无 dom 的 ui 库, 所以我觉得事情并没有这么简单, 趁着元旦放假, 抽出一下午时间, 本单身肥宅猿测试了下 w3c 提供的选择器, 也当是踩一回 uni/ 小程序的坑吧
具体支持情况见下表(Y 表示支持,N 表示不支持)

选择器
css 版本
h5
安卓
ios
微信小程序
备注

.class
css1
Y
Y
Y
Y

#id
css1
Y
Y
Y
Y

*
css2
Y
N
N
N

element
css1
Y
Y
Y
Y
注意类似于 html,body 这样的选择器, 非 h5 端会被转成 page

element,element
css1
Y
Y
Y
Y

element>element
css2
Y
Y
Y
Y

element+element
css2
Y
Y
Y
Y

[attribute]
css2
Y
Y
Y
Y
1.h5 端使用 uniapp 标签属性时, 编译后该属性可能会消失, 导致该选择器 ” 失效 ”, 如,view 的 hover-class 属性 2. 微信小程序 /app 端使用非规范的属性, 如,<view qwe-rt=”asd”></view> 在编译到微信小程序 /app 时会消失同样导致该选择器 ” 失效 ”

[attribute=value]
css2
Y
Y
Y
Y
同[attribute]

[attribute~=value]
css2
Y
Y
Y
Y
同[attribute]

[attribute|=value]
css2
Y
Y
Y
Y
同[attribute]

:link
css1
Y



没有找到办法在非 h5 上生成 a 标签

:visited
css1
Y



没有找到办法在非 h5 上生成 a 标签

:active
css1
Y
Y
Y
Y
在非 h5 的其他三端上表现与 <view hover-class=”xxx”> 属性一致(只测试了 view 标签与 text 标签)

:hover
css1
Y
Y
Y
Y
表现基本同:active 但是要取消该状态是要点击其他标签(让 hover 转移到其他标签上)

:focus
css2
N
N
N
N
1.h5 中会把 <input /> 编译成一个 uni-input>div>input+div.input-placeholder 的结构, 在 css 代码中写的类似于 input:focus{background: #F00;}的样式, 基本上是设置在 uni-input 这个标签上的, 所以期望 input 的 focus 样式并不会出现 (所以 h5 是因为 uni-app 对 css 代码的编译逻辑导致不支持 input 的:focus 选择器)2. 类似于 button 这些本来在正常 html 标签中是能在点击时获得 focus 状态的但在 uniapp 中,h5 会编译成 uni-button 标签, 这些标签没发现它能在点击后获得 focus 状态 3. 其他三端虽然没像如上描述那样转,(直接转成一个 input._input,button._button) 但是却不支持 focus 状态不知道是不是官方 (dcloud/ 微信) 故意的

:first-letter
css1
Y
Y
Y
Y
注意别踩坑

:first-line
css1
Y
Y
Y
Y
注意别踩坑

:first-child
css2
Y
Y
Y
Y

:before
css2
Y
Y
Y
Y

:after
css2
Y
Y
Y
Y

:lang(language)
css2
Y
N
N
N

element1~element2
css3
Y
Y
Y
Y

[attribute^=value]
css3
Y
Y
Y
Y
同[attribute]

[attribute$=value]
css3
Y
Y
Y
Y
同[attribute]

[attribute*=value]
css3
Y
Y
Y
Y
同[attribute]

:first-of-type
css3
Y
Y
Y
Y

:last-of-type
css3
Y
Y
Y
Y

:only-child
css3
Y
Y
Y
Y

:nth-child(n)
css3
Y
Y
Y
Y

:nth-last-child(n)
css3
Y
Y
Y
Y

:nth-of-type(n)
css3
Y
Y
Y
Y

:nth-last-of-type(n)
css3
Y
Y
Y
Y

:last-child
css3
Y
Y
Y
Y

:root
css3
Y
N
N
N
h5 端的支持只能是在 app.vue 的 style 标签里写的或者 @import 的样式里才能用:root

:empty
css3
Y
Y
Y
Y

:target
css3
Y



没有找到办法在非 h5 上实现锚点

:enabled
css3
N
N
N
N
类似于:focus, 可使用类似于 button:not([disabled])的方案代替

:disabled
css3
N
N
N
N
类似于:focus, 但是可以使用类似于 button[disabled]的方案代替但是只写 button[disabled]权重可能不够 h5 端写 input[disabled]无效, 原因见:focus 备注但是非 h5 端可以写 input[disabled]

:checked
css3
N
N
N
N
同:disabled

:not(selector)
css3
Y
Y
Y
Y

::selection
css3
Y
Y
N
ios:N 安卓:Y

至于其他厂商的小程序我也没有踩坑经验但是可参考微信小程序的兼容毕竟是微信把小程序推起来之后其他厂商才开始出小程序(最开始的时候支付宝小程序抄微信小程序源码事件还有人记得不)

(好像不弄套自己家的小程序出来, 自己就不是大厂了似得)求求你别更新了, 我学不过来了.jpg 手动狗头.jpg

正文完
 0