首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

纯JS实现按钮抖动效果

Sonder
2022-12-26
1385字
3分钟
浏览 (1.4k)

1626334075-d4f5c2c94881b8d.gif
复制代码
<button class="btn" id="btn">Just a button</button>
复制代码
body {
   min-height: 100vh;
   font-family: Roboto,Arial;
   display: flex;
   justify-content: center;
   align-items: center;
   background: #1499f7;
}

.btn {
   -webkit-appearance: none;
   border: 0;
   position: relative;
   height: 63px;
   width: 240px;
   padding: 0;
   cursor: pointer;
   border-radius: 32px;
   overflow: hidden;
   -webkit-mask-image: -webkit-radial-gradient(white,black);
}
复制代码
document.getElementById('btn').addEventListener('click', function(e) {
   Shaking(e.target)
})

function Shaking(el) {
   const maxDistance = 5 // 抖动偏移距离
   const interval = 12 // 抖动快慢,数字越小越快,太小DOM反应不过来,看不出动画
   const quarterCycle = 8 // 一次完整来回抖动的四分之一周期
   let curDistance = 0
   let direction = 1
   const timer = setInterval(function() {
       if (direction > 0) {
           curDistance++
           if (curDistance === maxDistance) {
               direction = -1
           }
       } else {
           curDistance--
           if (curDistance === -maxDistance) {
               direction = 1
           }
       }
       el.style.left = curDistance + 'px';
   }, interval)
   setTimeout(function() {
       clearInterval(timer)
       el.style.left = '0 px';
   }, maxDistance * interval * quarterCycle);
}
下一篇 / Element UI - el-select 同时获取 value 和 label 的值

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)