请编个带目录文档微信小程序代码
时间: 2024-05-16 18:15:35 浏览: 11
以下是一个简单的带目录的文档微信小程序代码示例:
```xml
<!-- index.wxml -->
<view class="container">
<!-- 目录 -->
<view class="menu">
<view class="menu-header">目录</view>
<scroll-view class="menu-content" scroll-y="true">
<block wx:for="{{catalog}}">
<view class="menu-item" bindtap="scrollToSection" data-index="{{index}}">
{{item.title}}
</view>
</block>
</scroll-view>
</view>
<!-- 文章正文 -->
<view class="article" id="article">
<block wx:for="{{catalog}}">
<view class="section" id="{{'section-' + index}}">
<view class="section-header">{{item.title}}</view>
<view class="section-content">{{item.content}}</view>
</view>
</block>
</view>
</view>
```
```javascript
// index.js
Page({
data: {
// 目录数据
catalog: [
{ title: '第一章', content: '第一章内容...' },
{ title: '第二章', content: '第二章内容...' },
{ title: '第三章', content: '第三章内容...' }
]
},
// 点击目录项跳转到对应章节
scrollToSection: function(e) {
let index = e.currentTarget.dataset.index;
let id = 'section-' + index;
wx.pageScrollTo({
selector: '#' + id,
duration: 300
});
}
})
```
```css
/* index.wxss */
.container {
display: flex;
flex-direction: row;
}
.menu {
width: 25%;
height: 100%;
background-color: #F5F5F5;
padding: 20rpx;
box-sizing: border-box;
}
.menu-header {
font-size: 28rpx;
font-weight: bold;
margin-bottom: 20rpx;
}
.menu-content {
height: calc(100% - 80rpx);
}
.menu-item {
font-size: 28rpx;
margin-bottom: 20rpx;
cursor: pointer;
}
.article {
width: 75%;
height: 100%;
padding: 20rpx;
box-sizing: border-box;
}
.section-header {
font-size: 32rpx;
font-weight: bold;
margin-bottom: 20rpx;
}
.section-content {
font-size: 28rpx;
line-height: 40rpx;
text-indent: 2em;
}
```
在上面的代码中,目录数据存储在 `data` 中的 `catalog` 数组中,每个目录项包含 `title` 和 `content` 两个属性。在页面渲染时,可以使用 `wx:for` 循环遍历目录数据,并为每个章节设置一个唯一的 `id`,以便在点击目录项时能够跳转到对应章节。通过 `wx.pageScrollTo` 方法可以实现平滑滚动到目标章节的效果。在样式方面,使用了 flex 布局实现了目录和文章正文的左右分栏。