Js实现圆周运动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0px;
margin: 0px;
}
.box5 {
position: relative;
height: 300px;
width: 300px;
border-radius: 50%;
background-color: chartreuse;
margin: 50px auto;
}
.circle {
height: 20px;
width: 20px;
border-radius: 50%;
position: absolute;
background-color: coral;
margin-left: -10px;
margin-top: -10px;
}
</style>
</head>
<body>
<!-- <div id="box5">
<div id="circle">
</div>
</div> -->
<div class="box5">
<div class="circle">
</div>
</div>
<script>
// 10.三角函数圆周运动
function cirMotion() {
// var box = document.getElementById("box5"); //使用getElementById获取元素
// var circle = document.getElementById("circle");
var box = document.querySelector(".box5");
var circle = document.querySelector(".circle");
var angle = 0; //定义每次走的角度
// var radius = box.offsetWidth / 2; //offerWidth得到元素盒模型的返回盒模型的宽度(包括width+左右padding+左右border)
var r = box.offsetWidth / 2;
clearInterval(timer);
var timer = setInterval(function () {
angle += 1;
var rad = Math.PI / 180 * angle; //得到角度的弧度值
var x = r * Math.cos(rad); //得到横坐标值
// var x = x + 5;
var y = r * Math.sin(rad); //得到纵坐标值
circle.style.left = r + x + "px";
circle.style.top = r - y + "px";
}, 20);
}
cirMotion();
</script>
</body>
</html>