这是我参与8月更文挑战的第7天,活动详情查看:8月更文挑战
作者:battleKing
仓库:Github、CodePen
博客:CSDN、掘金
反馈邮箱:myh19970701@foxmail.com
特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系笔者授权
背景
双击点赞动画:是指用手指点击两下特定的区域,就会自动完成点赞操作,这种动画在 桌面端 并不常见,因为在桌面端我们可以用 鼠标精准的点击到点赞按钮,只要 一次点击 就可以完成点赞操作,双击点赞 显得鸡肋,但是自从 4G 时代到来后,移动端 的设备大幅增加,但移动端以前都是 小屏时代,点赞按钮 太大容易 遮挡视线,太小又不容易 精准点击 ,所以很多企业就采用双击点赞的方式来达到更好的 交互体验,其中 字节跳动 公司旗下的 抖音 应该是把双击点赞运用的最成熟软件之一。所以我们今天就一起来学习一下它是如何使用代码实现的。
最终效果
一、导入 Font Awesome 图标库
<script src="https://use.fontawesome.com/ab349f0a54.js" ></script>
二、添加 HTML 文件
<h3>Double click on the image to <i class="fa fa-heart"></i> it</h3>
<small>You liked it <span id="times">0</span> times</small>
<div class="loveMe"></div>
三、添加 CSS 文件
先初始化页面
- 设置
*为box-sizing: border-box - 设置
body来使整个项目居中
* {
box-sizing: border-box;
}
body {
text-align: center;
overflow: hidden;
margin: 0;
}
主要的 CSS 代码
h3 {
margin-bottom: 0;
text-align: center;
}
small {
display: block;
margin-bottom: 20px;
text-align: center;
}
.fa-heart {
color: red;
}
.loveMe {
height: 440px;
width: 300px;
background: url('https://images.hdqwalls.com/download/lisa-blackpink-4k-mg-1920x1080.jpg') no-repeat center center/cover;
margin: auto;
cursor: pointer;
max-width: 100%;
position: relative;
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
overflow: hidden;
}
.loveMe .fa-heart {
position: absolute;
animation: grow 0.6s linear;
transform: translate(-50%, -50%) scale(0);
}
@keyframes grow {
to {
transform: translate(-50%, -50%) scale(10);
opacity: 0;
}
}
四、添加 JS 文件
主要逻辑
const loveMe = document.querySelector('.loveMe')
const times = document.querySelector('#times')
let clickTime = 0
let timesClicked = 0
loveMe.addEventListener('click', (e) => {
if (clickTime === 0) {
clickTime = new Date().getTime()
} else {
if ((new Date().getTime() - clickTime) < 800) {
createHeart(e)
clickTime = 0
} else {
clickTime = new Date().getTime()
}
}
})
const createHeart = (e) => {
const heart = document.createElement('i')
heart.classList.add('fa')
heart.classList.add('fa-heart')
const x = e.clientX
const y = e.clientY
const leftOffset = e.target.offsetLeft
const topOffset = e.target.offsetTop
const xInside = x - leftOffset
const yInside = y - topOffset
heart.style.top = `${yInside}px`
heart.style.left = `${xInside}px`
loveMe.appendChild(heart)
times.innerHTML = ++timesClicked
setTimeout(() => heart.remove(), 1000)
}
❤️ 感谢大家
如果本文对你有帮助,就点个赞支持下吧,你的「赞」是我创作的动力。
如果你喜欢这篇文章的话,可以「点赞」 + 「收藏」 + 「转发」 给更多朋友。