第一种
<style>
#img{
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
}
</style>
<body>
<img src="./image/1.jpg" id="img" >
<script>
//3、浮动广告(页面中一张广告图片不断的变化位置)
let image = document.getElementById('img');
function float() {
image.style.transition = 'all 1s linear';
let r = Math.trunc(Math.random() * (screen.width - image.width))
image.style.left = `${r}px`
r = Math.trunc(Math.random() * (screen.height - image.height))
image.style.top = `${r}px`
}
setInterval(float, 1000)
</script>
</body>
第二种
<style>
#dt {
width: 200px;
height: 150px;
position: absolute;
}
</style>
<body>
<div id="dt">
<img src="./image/1.jpg" alt="" width="200" height="150">
</div>
<script>
function updatePosition() {
//1.获取随机数
let my_top = Math.random() * 600
let my_left = Math.random() * 1000
//2.获取div
let div = document.querySelector('#dt')
div.style.top = my_top + 'px'
div.style.left = my_left + 'px'
}
setInterval(updatePosition, 1000)
</script>
</body>
第三种
<style>
* {
margin: 0;
padding: 0;
}
body {
position: relative;
height: 100vh;
}
img {
position: absolute;
height: 100px;
width: 160px;
}
</style>
</head>
<body>
<img src="./image/1.jpg" />
<script>
const img = document.querySelector('img');
const body = document.querySelector('body');
const w = body.offsetWidth;
const h = body.offsetHeight;
let left = 0,
up = 0;
let leftBorder = true,
upBorder = true;
setInterval(() => {
if (left === 0) leftBorder = true;
if (up === 0) upBorder = true;
if (left === w - img.offsetWidth) leftBorder = false;
if (up === h - img.offsetHeight) upBorder = false;
leftBorder ? left++ : left--;
upBorder ? up++ : up--;
img.style.left = left + 'px';
img.style.top = up + 'px';
}, 1);
</script>
</body>