效果如下:
代码如下(可以直接复制在本地观看效果):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
.box {
margin-top: 200px;
width: 228px;
height: 156px;
position: relative;
background-color: pink;
animation-name: test, tomove;
animation-duration: 1s;
animation-timing-function: linear;
/* 匀速 */
}
.con {
width: 50px;
height: 156px;
background-color: black;
color: white;
text-align: center;
}
.first,
.second,
.third {
margin-top: 200px;
width: 50px;
height: 50px;
border-radius: 50%;
background: red;
position: absolute;
transform: translate(-50%, -50%);
}
.first {
left: 900px;
top: 0;
}
.second {
left: 600px;
top: 300px;
}
.third {
left: 300px;
top: 0px;
}
</style>
</head>
<body>
<div class="box">
<div class="con">头部</div>
</div>
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>
<script type="text/javascript">
var newx = 600
var oldx = 900
var newy = 300
var oldy = 0
var i = 0
carmove(i)
setTimeout(
() => {
newx = 300
oldx = 600
newy = 0
oldy = 300
i = i + 2
$('.box').css({
"animation-duration": i + "s", //1s后上个动画执行完毕,让新的动画时间为2-1=1s
"animation-fill-mode": "forwards", // "animation-fill-mode": "forwards", 最后一帧结束后停止
})
carmove(i)
},
1000
);
function getTanDeg(y) {
return Math.atan(y) * 180 / Math.PI
}
function carmove(i) {
var deg = getTanDeg((oldx - newx) / (oldy - newy)) //计算两次坐标偏转的角度,自己可以画图看下
console.log(deg)
$(".box").css("transform", "translate(-50%, -50%) rotate(" + deg + "deg)"); //translate(-50%,-50%)让盒子位于自己中心
var style = document.styleSheets[0] //获取html中第1个样式表中的第一条规则
console.log(style.cssRules)
style.insertRule("@keyframes test{from{ left: " + oldx + "px; }to{ left: " + newx + "px;}}", i); //js写入样式
style.insertRule("@keyframes tomove{from{ top: " + oldy + "px; }to{ top: " + newy + "px;}}", 1 + i);
}
</script>
</body>
</html>