一、项目背景与技术选型
微信官方推出的WEUI框架是专为微信生态设计的前端UI库,其遵循BEM(Block Element Modifier)国际命名规范。本次实践我们将通过构建一个标准按钮组件,展示如何:
- 使用BEM规范组织代码结构
- 实现WEUI的页面布局体系
- 创建可复用的样式模块
二、BEM规范实践解析
2.1 页面结构划分
html
<div class="page">
<div class="page__hd">...</div>
<div class="page__bd">...</div>
<div class="page__ft">...</div>
</div>
page
作为Block容器__hd
/__bd
/__ft
作为Element元素- 命名规则:
[block]__[element]
2.2 样式命名规范
css
/* 区块样式 */
.page { ... }
/* 元素样式 */
.page__hd { ... }
/* 独立组件 */
.wei-btn { ... }
三、核心代码实现剖析
3.1 页面基础结构
html
<div class="page">
<header class="page__hd">
<h1 class="page__title">Button</h1>
<p class="page__desc">按钮</p>
</header>
<main class="page__bd">
<div class="button-sp-area">
<a href="#" class="weui-btn">主要操作</a>
</div>
</main>
</div>
3.2 样式层实现要点
3.2.1 全局重置(common.css)
css
/* 现代CSS Reset方案 */
html, body { height: 100%; }
.page {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ededed;
overflow-y: auto;
}
.page__title {
font-size: 20px;
font-weight: 400;
}
.page__desc {
color: rgba(0,0,0,0.5);
font-size: 14px;
}
3.2.2 按钮组件(button.css)
css
.button-sp-area {
margin: 15px auto;
padding: 15px;
text-align: center;
}
.weui-btn {
display: block;
width: 184px;
margin: 0 auto;
padding: 12px 24px;
font-size: 17px;
line-height: 1.411;
background-color: #07c160;
color: #fff;
border-radius: 4px;
transition: opacity 0.3s;
}
.wei-btn:active {
opacity: 0.8;
}
四、实现效果与最佳实践
4.1 视觉呈现效果
4.2 开发实践建议
- 分层结构
- 页面容器(page)
- 内容区块(hd/bd/ft)
- 功能组件(button)
- 响应式处理
css
@media (max-width: 768px) {
.page__hd { padding: 20px; }
.wei-btn { width: 90%; }
}
- 状态管理
css
.wei-btn--disabled {
background-color: #ddd;
cursor: not-allowed;
}
.wei-btn--loading {
position: relative;
padding-right: 40px;
}
五、技术总结
- BEM优势体现
- 清晰的层级关系
- 避免样式污染
- 提升可维护性
- WEUI设计特点
- 移动优先的布局方案
- 符合微信设计语言
- 轻量级实现(当前示例CSS仅2KB)
- 扩展方向
- 主题色系统配置
- 动效集成方案
- 多尺寸适配方案
通过本实践,我们不仅掌握了WEUI框架的基本使用方法,更深入理解了BEM规范在前端工程化中的重要作用。这种模块化的开发方式能够显著提升团队协作效率和项目的可维护性。