订阅按钮在很多应用上都能看到,不同应用的订阅按钮有一定的区别,这篇主要给大家分享类似抖音的动画的订阅按钮效果,具体的效果如下,还是比较美观好看的,那么这样的效果要怎样做呢?
使用jQuery的toggleClass()方法,添加删除类active
分别为原本的和active的元素设置样式,使用css的transition属性,定义变化时间,速度等
使用css的animation为active元素设置变化动画
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<!-- 简单起见,用了div。其实用button也行,需要设置一下样式才好看^_^-->
<!-- 还没有学习<svg>,使用<svg>效果也许会更好-->
<div id="followBtn">
<div id="line1"></div>
<div id="line2"></div>
</div>
<script src="index.js"></script>
</body>
</html>
JS
$(function () { // jQuery入口函数
$('#followBtn').click(function (e) { // 绑定点击事件
$('#followBtn').toggleClass('active');
$('#line1').toggleClass('active');
$('#line2').toggleClass('active');
});
})
CSS
body {
width: 1024px;
margin: 0 auto; /* 居中 */
}
#followBtn {
position: relative;
display: block;
width: 100px;
height: 100px;
margin: 100px auto;
border-radius: 100px; // 使div变为圆形
background-color: #ccc;
transition: all linear .5s; // 定义样式转换时的过度动画的属性
}
#followBtn.active {
background-color: crimson;
}
#line1 {
position: absolute; /*绝对定位,定位基于最近的一个已经定位(relative, absolute, fixed)的祖先元素*/
left: 25px;
top: 46px;
display: block;
width: 50px;
height: 8px;
border-radius: 5px;
background-color: crimson;
transition: all linear .5s;
}
#line2 {
position: absolute;
left: 25px;
top: 46px;
display: block;
width: 50px;
height: 8px;
border-radius: 8px;
background-color: crimson;
transform: rotate(90deg); /* 旋转90度 */
transition: all linear .5s;
}
#line1.active {
background-color: #ccc;
/*触发动画,forwards表示动画结束后,元素样式保留为动画的最后一个关键帧的样式*/
animation: line1 .5s ease-in-out forwards;
}
#line2.active {
background-color: #ccc;
animation: line2 .5s ease-in-out forwards;
}
/* @keyframes定义动画 */
@keyframes line1 {
50% {
width: 8px;
height: 8px;
left: 20px;
top: 52px;
border-radius: 8px;
}
100% {
width: 30px;
left: 20px;
top: 52px;
transform: rotate(45deg);
}
}
@keyframes line2 {
50% {
width: 8px;
height: 8px;
border-radius: 8px;
left: 35px;
}
100% {
width: 50px;
left: 35px;
transform: rotate(-45deg);
}
}
jQuery3以下的版本,不能正确的给修改SVG元素的类。
//.attr()方法对于SVG是有效的,所以如果你必须使用jQuery的话
// 使用
$("#item").attr("class", "oldclass newclass"); // 而不是 .addClass("newclass")
// 使用
$("#item").attr("class", "oldclass"); // 而不是 .removeClass("newclass")
// 原生JS解决办法
var element = document.getElementById("item");
// 使用
element.setAttribute("class", "oldclass newclass");
// 使用
element.setAttribute("class", "oldclass");
以上就是用CSS实现一个动画的订阅按钮效果的介绍,本文只是提供了一种实现思路,代码仅供参考,需要的朋友可以了解看看。