1.效果图
2.实现代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<style>
body{
margin: 0;
}
.big{
text-align: center;
font-size: 100px;
position: relative;
width: 1000px;
height: 500px;
border: 2px solid #000;
margin: 50px auto;
}
img{
width: 120px;
height: 100px;
}
.box{
width: 120px;
height: 120px;
background: green;
border-radius: 8px;
text-align: center;
line-height: 50px;
color: #fff;
font-size: 12px;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="big">
<h2>感谢爱如潮水老铁!</h2>
<div class="box"><img src="1.jpg" alt=""></div>
</div>
<script>
$(function(){
fn();
var Timer;
var x = 0;
var y = 0;
//父集的宽度
var l = $('.box').width();
//父集的高度
var t = $('.box').height();
//盒子的宽度
var bl = $('.big').width();
//盒子的高度
var bt = $('.big').height();
//差值
var w = bl - l;
var h = bt - t;
//开启定时器
var timer = setInterval(fn,10);
function fn(){
//当移动到最右侧时反弹,如果这个条件成立则方块向右侧移动,下面都一样
if(parseInt(x/w)%2 == 0){
x2=x%w;
$('.box').css({
left: x2
});
x++;
}else{
x1=x%w;
$('.box').css({
left: w-x1
});
x++;
}
if(parseInt(y/h)%2 == 0){
y2=y%h;
$('.box').css({
top: y2
});
y++;
}else{
y1=y%h;
$('.box').css({
top: h-y1
});
y++;
}
}
$('.box').mouseenter(function() {
clearTimeout(timer);
clearTimeout(Timer);
});
$('.box').mouseleave(function() {
Timer = setInterval(fn,10);
});
})
</script>
</body>
</html>