# DrawerContainer **Repository Path**: filebird/DrawerContainer ## Basic Information - **Project Name**: DrawerContainer - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-11-02 - **Last Updated**: 2021-11-02 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ArkUI中JS开发基础:自定义侧滑菜单 ### **前言** 新世界的大门已打开,关也关不住! 本项目基于ArkUI中JS扩展的类Web开发范式,关于语法和概念直接看官网官方文档地址:[基于JS扩展的类Web开发范式1](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-js-overview-0000000000500376) [基于JS扩展的类Web开发范式2](https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-framework-file-0000000000611396) 侧滑菜单其实在平时挺常见的(本项目中设置了两种风格) ### 效果演示 ![](gif/demo.gif) ![](gif/demo1.gif) ### 实现思路 页面和逻辑都在此目录下:entry/js/default/pages/drawer **主要使用onTouch相关事件,滑动改变菜单布局或内容布局的left偏移量,手指抬起使用动画完成偏移量** 1、onTouch相关事件(只贴出了关键代码) ```js /** * 触摸按下 */ onTouchStart(event) { // 记录首次按下的x坐标 this.pressX = event.touches[0].localX // 记录上次的x坐标 this.lastX = this.pressX ..... }, /** * 触摸移动 */ onTouchMove(event) { // 当前x坐标 let localX = event.touches[0].localX // 计算与上次的x坐标的偏移量 let offsetX = this.lastX - localX; // 记录上次的x坐标 this.lastX = localX // 累计偏移量 this.offsetLeft -= offsetX // 设置偏移量的范围 ..... } /** * 触摸抬起 */ onTouchEnd(event) { ...... // 手指抬起,根据情况,判断toX的值,也就是判断关闭或开启菜单的情况 // 当移动偏移量大于菜单一半宽度,完全打开菜单,否则反之 if (this.offsetLeft > this.menuWidth / 2) { toX = this.menuWidth } else { toX = 0 } ...... // 开启动画 this.startAnimator(toX) } /** * 开启动画 */ startAnimator(toX) { // 设置动画参数 let options = { duration: ANIMATOR_DURATION, // 持续时长 fill: 'forwards', // 启停模式:保留在动画结束状态 begin: this.offsetLeft, // 起始值 end: toX // 结束值 }; // 更新动画参数 this.animator.update(options) // 监听动画值变化事件 this.animator.onframe = (value) => { this.offsetLeft = value this.changeMenuOffsetLeft() } // 开启动画 this.animator.play() }, ``` 2、showStyle: 0 第一种样式下,解决设置z-index之后菜单界面在内容下面,但点击事件却还在内容上面的问题。 - 初始化设置left偏移量 - 动画结束,判断菜单是否关闭,关闭直接设置菜单偏移量为负的菜单宽度 ```js /** * 界面显示 */ onShow() { ..... // 设置菜单偏移量为负的菜单宽度,为了解决z-index设置后,菜单界面到内容下面, // 事件还停留到内容上面,导致点击菜单区域,响应的还是菜单点击事件 this.menuOffsetLeft = -this.menuWidth } ``` ### 使用说明 ```html
``` 2、更改样式,更改js中showStyle的值 ```js export default { data: { .... showStyle: 0, // 显示样式:0菜单在下面,1菜单在上面 } } ``` ### **结尾** 每天进步一点点、需要付出努力亿点点。 ### 版权和许可信息 ``` Copyright [2021] [liangqingsong of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ```