<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车</title>
<style>
* {
margin: 0;
padding: 0;
}
#addToCart {
position: fixed;
left: 600px;
cursor: pointer;
width: 100px;
height: 40px;
line-height: 40px;
border: 1px solid deeppink;
text-align: center;
color: deeppink;
top: 500px;
}
#addToCart:hover {
color: #fff;
background-color: deeppink;
}
#shopCart {
position: fixed;
right: 0;
top: 200px;
color: red;
}
#shopNum {
width: 60px;
height: 25px;
background: deeppink;
color: black;
text-align: center;
line-he0ight: 25px;
}
.active {
width: 25px;
height: 25px;
background: skyblue;
position: absolute;
border-radius: 50%;
}
</style>
<body>
<div id="addToCart">
添加到购物车
</div>
<div id="shopCart">
购物车
<p id="shopNum"></p>
</div>
</body>
</html>
<script src="../public.js"></script>
<script type="text/javascript">
var addToCart = $id("addToCart");
var shopCart = $id("shopCart");
var shopNum = $id("shopNum");
var num = 0;
//做该题要利用抛物线公式
//找到起始点
//找到终点
//定义一个最高点
//根据以上三点求出抛物线y=a*x*x+b*x+c中的a,b,c
//点击添加购物车后创建一个小球
//小球的起始位置为起始点
//给小球定义一个起始坐标,让小球按照抛物线路径进行运动
//小球在水平方向上要向右进行运动
addToCart.onclick = function () {
/* 找到起始点 */
var startPoint = {
x: addToCart.offsetLeft + addToCart.offsetWidth / 2,
y: addToCart.offsetTop
}
/* 找到终点 */
var endPoint = {
x: shopCart.offsetLeft + shopCart.offsetWidth / 2,
y: shopCart.offsetTop
}
/* 自己定义一个最高点 */
var topPoint = {
x: endPoint.x - 100,
y: endPoint.y - 100
}
/* 套用公式求出a,b,c */
var a = ((startPoint.y - endPoint.y) * (startPoint.x - topPoint.x) - (startPoint.y - topPoint.y) * (startPoint.x - endPoint.x)) / ((startPoint.x * startPoint.x - endPoint.x * endPoint.x) * (startPoint.x - topPoint.x) - (startPoint.x * startPoint.x - topPoint.x * topPoint.x) * (startPoint.x - endPoint.x));
var b = ((endPoint.y - startPoint.y) - a * (endPoint.x * endPoint.x - startPoint.x * startPoint.x)) / (endPoint.x - startPoint.x);
var c = startPoint.y - a * startPoint.x * startPoint.x - b * startPoint.x;
/* 点击添加购物车后添加小球 */
var ball = document.createElement("div")
ball.className = "active";
/* 这里把小球添加到body中,在下边给小球进行位置说明,不需要把小球添加到div中*/
document.body.appendChild(ball)
ball.style.left = addToCart.offsetLeft + addToCart.offsetWidth / 2 + "px"
ball.style.top = addToCart.offsetTop + "px"
/* 小球起始位置水平方向建立X坐标 */
var x = ball.offsetLeft;
var y = 0
/* 建立一个定时器实时获取x的位置 */
var timer = setInterval(function () {
/* x在水平方向步长为3 */
x += 3;
y = a * x * x + b * x + c;
ball.style.left = x + "px";
ball.style.top = y + "px";
if (ball.offsetLeft == endPoint.x) {
clearInterval(timer);
ball.remove();
num++;
shopNum.innerHTML = num;
}
}, 10)
}
效果图``
![在这里插入图片描述](https://img-blog.csdn.net/20181023195135847?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjMzNjQz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70