any-touch 一個手勢庫javascript
預覽1css
若是預覽1打不開, 點我html
注: 本文僅用來說解drawer的基本原理, 還有不少邊界處理的細節你們能夠後續自行補充做爲練習.vue
<!-- 觸發把手 -->
<div class="com-drawer-handler" id="j-com-drawer-handler"></div>
<!-- 抽屜 -->
<div class="com-drawer" id="j-com-drawer">
<img class="avator" src="https://s.cdpn.io/profiles/user/406915/80.jpg?1511329408" width="100%">
<p align="center">
鐵皮飯盒
</p>
<a class="github" href="https://github.com/any86/any-touch">github : any-touch</a>
<div>
<script src="https://unpkg.com/any-touch/dist/AnyTouch.umd.js"></script>
複製代碼
.com-drawer-handler {
height: 100vh;
background: rgba(252, 252,252, 0);
width: 45px;
position: fixed;
z-index: 2;
top: 0;
left: 0;
}
.com-drawer {
padding: 30px;
height: 100vh;
min-width: 10vw;
position: fixed;
top: 0;
left: 0;
z-index: 3;
box-shadow: 1px 2px 3px rgba(0, 0, 0, 0.1);
.avator {
touch-action: none;
display: block;
width: 60%;
border-radius: 100%;
margin: 15px auto;
}
.github {
padding: 5px 15px;
background: #000;
color: #fff;
text-decoration: none;
display: block;
text-align: center;
border-radius: 6px;
margin-top: 60px;
}
}
.animated {
transition: all 200ms;
}
複製代碼
// 抽屜部分
let offsetX = 0;
const elDrawer = document.getElementById("j-com-drawer");
const minX = 0 - elDrawer.offsetWidth;
const at = new AnyTouch(elDrawer);
at.on("panmove", ({ deltaX }) => {
offsetX += deltaX;
if (0 <= offsetX) {
offsetX = 0;
}
elDrawer.style.transform = `translateX(${offsetX}px)`;
});
at.on("panend", () => {
offsetX = minX / 2 < offsetX ? 0 : minX;
elDrawer.style.transform = `translateX(${offsetX}px)`;
elDrawer.classList.toggle(animated, true);
});
// 把手
const elHandler = document.getElementById("j-com-drawer-handler");
const atHandler = new AnyTouch(elHandler, { isPreventDefault: false });
atHandler.on("panmove", ({deltaX}) => {
offsetX+= deltaX;
offsetX = 0 < offsetX ? 0 : offsetX;
elDrawer.style.transform = `translateX(${offsetX}px)`;
});
複製代碼
這裏是用純js實現的版本, 若是用vue或者react代碼量會更少, 有興趣的同窗能夠自行實現或者須要的人多, 我會再寫個vue版本的例子(react我也不會, 我得找同事幫寫個demo, 嘿). 太晚了,寫的倉促, 若是錯誤請指出, 我會當即修改.java
any-touch由typescript編寫, 若有興趣歡迎訪問個人其餘幾篇關於代碼講解的文章:react
用typescript開發手勢庫 - (1)web開發經常使用手勢有哪些?git
用TypeScript開發手勢庫 - (2)tsconfig.json & rollup.config.js & npxgithub