1.translateX():水平方向移动
2./ 本身样式发生改变,会以动画形式过度,时长为2s /
animation: all 2s;
3./ 鼠标悬停在上面时触发 box:hover /
.box:hover{
width: 400px;
height: 300px;
border-radius: 20px;
background-color: yellow;
}
4.
<script>
// 根据id获取元素,拿到处理对象
let box = document.getElementById("box")
let ball = document.getElementById("ball")
// 获取对象的宽高
let box_w = box.clientWidth
let box_h = box.clientHeight
let ball_w = ball.clientWidth
let ball_h = ball.clientHeight
console.log(box_w,box_h)
console.log(ball_w,ball_h)
</script>
5.小球移动代码块,采用节点移动跟随对样式进行修改,x_speed为移动速度
<script>
// 根据id获取元素,拿到处理对象
let box = document.getElementById("box")
let ball = document.getElementById("ball")
// 获取对象的宽高
let box_w = box.clientWidth
let box_h = box.clientHeight
let ball_w = ball.clientWidth
let ball_h = ball.clientHeight
// 对样式进行修改
box.style.position = "relative"
ball.style.position = "absolute"
ball.style.left = "0"
// 时间循环方法 1秒=1000毫秒
let left_pos = 0
let x_speed = 5
setInterval(function(){
ball.style.left = left_pos+ "px"
left_pos+=x_speed
},50)
</script>
6.小球移动完整代码
用if来控制小球,使其不会跑出框外,用random随机数更改颜色
<!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>
.box {
width: 400px;
height: 400px;
border: 1px solid;
}
.ball {
width: 80px;
height: 80px;
background-color: lightblue;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="ball" id="ball"></div>
</div>
<script>
// 拿到要处理的对象
let box = document.getElementById("box")
let ball = document.getElementById("ball")
// 获取对象的宽高
let box_w = box.clientWidth
let box_h = box.clientHeight
let ball_w = ball.clientWidth
let ball_h = ball.clientHeight
// 对样式的修改
box.style.position = "relative"
ball.style.position = "absolute"
// 时间循环方法 1秒=1000毫秒
let left_pos = 0, top_pos = 0
let x_speed = 5, y_speed = 4
let colors = ["lightpink", "lightsalmon", "lightblue", "darkgray"]
setInterval(function() {
ball.style.left = left_pos + "px"
ball.style.top = top_pos + "px"
let color = Math.floor(Math.random()*4)
if (left_pos >= box_w - ball_w || left_pos < 0) {
x_speed *= -1
ball.style.backgroundColor = colors[color]
}
if (top_pos >= box_h - ball_h || top_pos < 0) {
y_speed *= -1
ball.style.backgroundColor = colors[color]
}
left_pos += x_speed
top_pos += y_speed
}, 30)
</script>
</body>
</html>