JavaScript實作簡單的圓球反彈運動
<!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>
.circle {
width: 100px;
height: 100px;
border: 1px solid #ccc;
border-radius: 50%;
background: #008c8c;
position: fixed;
left: 100px;
top: 100px;
}
</style>
</head>
<body>
<div ></div>
<script>
var circle = document.querySelector(".circle");
var style = window.getComputedStyle(circle);
var disX = 10,
disY = 10,
time = 30;
circle.onclick = function () {
setInterval(function () {
var left = parseFloat(style.left);
var top = parseFloat(style.top);
var newLeft = left + disX;
var newTop = top + disY;
if (left < 0) {
newLeft = 0;
disX = -disX;
}
if (left > document.documentElement.clientWidth - parseInt(style.width)) {
newLeft = document.documentElement.clientWidth - parseInt(style.width);
disX = -disX;
}
if (top < 0) {
newTop = 0;
disY = -disY;
}
if (top > document.documentElement.clientHeight - parseInt(style.height)) {
newTop = document.documentElement.clientHeight - parseInt(style.height);
disY = -disY;
}
circle.style.left = newLeft + "px";
circle.style.top = newTop + "px";
}, time);
}
</script>
</body>
</html>
index.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/104030.html
標籤:JavaScript
下一篇:TypeScript---函式
