<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>拍一拍摇晃头像</title>
<style>
.face {
cursor: grab;
width: 200px;
height: 200px;
border-radius: 50px;
background: orange;
text-align: center;
font-size: 60px;
line-height: 180px;
font-weight: bold;
color: white;
/*禁止选中文本*/
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
-khtml-user-select: none;
user-select: none;
}
.face:active {
cursor: grabbing;
}
/*【核心摇晃代码】----------------------------------------------------------------*/
[sg-pat-face-shaking] {
animation: sg-pat-face-shaking .5s ease-in-out alternate forwards;
}
@keyframes sg-pat-face-shaking {
10% {
transform: translate(2px, -2px) rotate(6deg);
}
25% {
transform: translate(-2px, -2px) rotate(-6deg);
}
50% {
transform: translate(1px, -1px) rotate(3deg);
}
85% {
transform: translate(-1px, -1px) rotate(-3deg);
}
100% {
transform: translate(0px, 0px) rotate(0deg);
}
}
</style>
</head>
<body>
<div class="face">头像</div>
</body>
<script>
//触发双击----------------------------------------------------------------
document.querySelector(".face").ondblclick = function () {
this.removeAttribute("sg-pat-face-shaking");
setTimeout(() => {
this.setAttribute("sg-pat-face-shaking", true);
// 实现手机振动效果 📳 📳 📳
(navigator.vibrate =
navigator.vibrate ||
navigator.webkitVibrate ||
navigator.mozVibrate ||
navigator.msVibrate),
navigator.vibrate && navigator.vibrate(50); //振动50毫秒
soundEffect.pat(
this.patIndex || (this.patIndex = 0),
this.patIndex >= 5 ? (this.patIndex = 1) : ++this.patIndex
); //播放拍一拍音效
}, 100);//延迟一点才会生效动画
};
</script>
</html>