// 小球飘动
<html>
<head>
<meta charset="utf-8" />
<title>会飘的小球</title>
<style>
div {
width: 100px;
height: 100px;
border-radius: 50px;
background: gold;
font-size: 20px;
line-height: 100px;
text-align: center;
top: 0;
left: 0;
position: absolute;
}
</style>
</head>
<body>
<div>飘啊飘</div>
</body>
<script>
var piao = document.getElementsByTagName('div')[0]
// 获取宽高
var width = parseInt(getComputedStyle(piao, null)['width'])
var height = parseInt(getComputedStyle(piao, null)['height'])
var xSpeed = 10
var ySpeed = 10
var timer = null
// 鼠标移入时
piao.onmouseover = function() {
clearInterval(timer)
}
// 鼠标移开时
piao.onmouseout = start
function start()
{
timer = setInterval(function() {
// 获取当前位置
var top = parseInt(getComputedStyle(piao, null)['top'])
var left = parseInt(getComputedStyle(piao, null)['left'])
// 修改偏移
top += ySpeed
left += xSpeed
// 判断边界
// 左右边界
if (left <= 0 || left+width >= window.innerWidth) {
xSpeed *= -1
}
// 上下边界
if (top <= 0 || top+height >= window.innerHeight) {
ySpeed *= -1
}
// 重新设置属性
piao.style.top = top + 'px'
piao.style.left = left + 'px'
}, 100)
}
// 调用
start()
</script>
</html>
小球飘动
猜你喜欢
转载自blog.csdn.net/weixin_43789195/article/details/85080654
今日推荐
周排行