微信小程序组件对于样式设置有许多坑点。这是一篇不完全避坑指南✍,接下来我将为大家来梳理这些坑点及避坑要点👉👉
坑点一
在自定义的 wxss 文件中,不允许使用标签选择器,ID 选择器,属性选择器
标签选择器
在组件中使用属性选择器,会影响当前和其他页面和其他组件中的同属性标签样式
<custom02/>
组件代码
<text id='content' class="content">
<text class="label">给自定义组件设置样式text</text>
</text>
- 组件
<custom01/>
和<custom02/>
(该组件中存在<text/>
标签)的wxss文件中配置如下代码
text {
color: lightseagreen;
}
- index.wxml中配置如下代码
<text>这是一个text标签</text>
- cate.wxml中配置如下代码
<custom02></custom02>
- cart.wxml中配置如下代码
<custom01></custom01>
|
|
|
ID选择器
在组件中使用ID选择器,组件内部样式不会生效
- 组件
<custom02/>
wxss文件中配置如下代码
#content {
color: lawngreen
}
- 组件
<custom02/>
wxml文件中配置如下代码
<view id='content' class="content son">
<text class="label">给自定义组件设置样式</text>
</view>
- cate.wxml中引用组件
<custom02></custom02>
属性选择器
在组件中使用属性选择器,组件内部样式不会生效
- 组件
<custom02/>
wxss文件中配置如下代码
[id=content] {
color: lawngreen;
}
- 组件
<custom02/>
wxml文件中配置如下代码
<view id='content' class="content son">
<text class="label">给自定义组件设置样式</text>
</view>
- cate.wxml中引用组件
<custom02></custom02>
坑点二
子选择器,只能用于 view 和 子组件,用于其他组件可能会出现样式失效的问题
- 组件
<custom02/>
wxss文件中配置如下代码
.content > .label {
color: lawngreen;
}
- 组件
<custom02/>
wxml文件中配置如下代码
//该组件内样式失效
<text id='content' class="content">
<text class="label">给自定义组件设置样式text</text>
</text>
//该组件样式生效
<view id='content' class="content">
<text class="label">给自定义组件设置样式view</text>
</view>
- cate.wxml中引用组件
<custom02></custom02>
坑点三
继承样式,例如:color\font 都会从组件外继承
- 在全局app.wxss文件中配置样式
.custom {
color: lightgreen;
}
- cart.wxml中引用组件
<view class="custom">
<custom02></custom02>
</view>
坑点四
全局样式、组件所在页面的样式文件中的样式都对自定义组件无效
<custom02/>
组件中代码
<text id="content" class="content son">
<text class="label test">给自定义组件设置样式</text>
</text>
- app.wxss全局样式文件配置代码
.label {
color: lightseagreen;
}
- 在cart.html文件中引入组件
<custom02/>
<custom02></custom02>
坑点五
不建议在 全局样式文件 以及 父级页面之间使用标签选择器设置样式,如果是在全局样式文件中设置样式,会影响项目中全部的相同组件,如果是再页面样式文件中设置样式,会影响当前页面所有的相同组件
坑点六
组件和组件使用者,如果使用了后代选择器,可能会出现一些非预期情况,会影响组件内部样式
- 在
<custom02>
组件js文件中设置options属性
Component({
options: {
styleIsolation: "shared"
}
})
- 在组件
<custom02>
的wxml中配置代码
<text id='content' class="content son">
<text class="label">给自定义组件设置样式text</text>
</text>
- 在cate.wxml文件中配置代码
<view class="custom parent">
<view>
<custom02 />
<view class="son test">我是父级页面中的结构</view>
</view>
</view>
- 在cate.wxss中配置代码
.parent .son {
color: lawngreen;
}
评论💻+ 点赞 🤞+ 收藏🧧,您的支持就是我最大的动力~😘