<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>对象在窗口无规则浮动</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="reset.css"/>
<style>
div{
position:absolute;
}
</style>
</head>
<body>
<div id="div" style="width: 800px;height:500px;background: pink;margin-top:50px;margin-left:100px;">
<div id="divImg" style="background:red;width:30;height:30;">
<p>刘美娇</p>
</div>
</div>
<button type="button" onclick="start();">开始</button>
<button type="button" onclick="end();">结束</button>
<script language="javascript" type="text/javascript">
function floatimg() {
//获取div左上角坐标,即距离body的距离,浮动对象起始位置
var x = $("#div").offset().left,
y = $("#div").offset().top;
//获取div自身的宽高,带内边距
var a = $("#div").innerWidth(),
b = $("#div").innerHeight();
//获取浮动对象在div内右下边最大X和Y的坐标值
var w = a-30,
h = b-30;
//随机产生坐标x和坐标Y的值(从左上角到右下角最大X和Y的坐标随机)
ranx = Math.floor(Math.random()*(w-x+1)+x);
rany = Math.floor(Math.random()*(h-y+1)+y);
//获取随机浮动对象,给对象样式确定坐标
var img1 = document.getElementById("divImg");
img1.style.left = ranx + "px";
img1.style.top = rany + "px";
$("#divImg").show();
}
function start(){
s = setInterval(function(){
// setTimeout("floatimg()", 500);
floatimg();
console.count('other 已经执行');
},Math.round(Math.random()* 10000));
}
function end(){
clearInterval(s);
$("#divImg").hide();
console.log('停止了');
}
</script>
</body>
</html>