先看布局
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.4.1.min.js"></script>
<script>
</script>
<style>
.car {
width: 300px;
height: 60px;
border:1px solid green;
position: fixed;
right:30px;
top:80px;
text-align: center;
line-height: 60px;
}
#btn{
width: 100px;
height: 30px;
background-color: red;
color: white;
position: fixed;
bottom:20px;
left: 50%;
margin-left:-50px;
text-align:center;
line-height: 30px;
}
.red{
width: 10px;
height: 10px;
background-color: red;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="red"></div>
<div class="car">购买金额<span>0</span>件商品</div>
<div id="btn">加入购物车</div>
</body>
</html>
逻辑
- 点击按钮,让小红点出现在按钮的位置
- 写动画效果,让小红点从按钮的位置移动到购物车的盒子那里
- 移动完毕后,让计数+1
- 优化代码,让初始状可见的小红点,不可见
- 优化代码,让运动结束后,小红点消失
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- <script src="jquery-3.4.1.min.js"></script>-->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function () {
// 获取btn标签,给它绑定一个click事件
$("#btn").click(function () {
$(".red").show();
var x = $("#btn").offset().left;
var y = $("#btn").offset().top;
// alert("btn的x坐标是"+x+"y坐标是"+y);
var btn_width = $("#btn").width();
var btn_height = $("#btn").height();
var red_width = $(".red").width();
var red_height = $(".red").height();
//拿到小红点,给一个初始的位置
// $(".red").css("left", x);
// $(".red").css("top", y);
var start_x = x+btn_width/2-red_width/2;
var start_y = y+btn_height/2-red_height/2;
$(".red").css({"left":start_x, "top":start_y});
//小红点终点的位置
// var end_x =?;
// var end_y = ?;
var car_x = $(".car").offset().left;
var car_y = $(".car").offset().top;
var end_x = car_x + $(".car").width()/2;
var end_y = car_y + $(".car").height()/2;
$(".red").animate({"left":end_x, "top":end_y},1000, function () {
$(".red").hide();
var num = $(".car span").html();
int_num = parseInt(num);
int_num += 1;
$(".car span").html(int_num)
// alert(int_num);
});
})
})
</script>
<style>
.car {
width: 300px;
height: 60px;
border:1px solid green;
position: fixed;
right:30px;
top:80px;
text-align: center;
line-height: 60px;
}
#btn{
width: 100px;
height: 30px;
background-color: red;
color: white;
position: fixed;
bottom:20px;
left: 50%;
margin-left:-50px;
text-align:center;
line-height: 30px;
}
.red{
width: 10px;
height: 10px;
background-color: red;
border-radius: 5px;
position: fixed;
left:0px;
top:0px;
z-index: 999;
display: none;
}
</style>
</head>
<body>
<div class="red"></div>
<div class="car">购买金额<span>0</span>件商品</div>
<div id="btn">加入购物车</div>
</body>
</html>