<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>前端页面实现标签漂浮碰壁变向</title>
</head>
<style>
* {
margin:0;
padding:0;
}
html,body{
width:100%;
height:100%;
}
.wrap {
width: 100%;height: 100%;
border: 1px solid gray;
position: relative;
box-sizing: border-box;
}
.box {
width: 100px;height: 100px;
border: 1px solid green;
position: absolute;
top: 100px;left: 200px;
border-radius: 50%;
}
</style>
<body>
<div class="wrap" id="wrap">
<div class="box" id="box"></div>
</div>
<script>
var wrap = document.getElementById("wrap");
var box = document.getElementById("box");
var a = 1;
var b = 1;
var w = wrap.offsetWidth - box.offsetWidth;
var h = wrap.offsetHeight - box.offsetHeight;
setInterval(function(){
var l = box.offsetLeft;
if(l == w || l == 0){
a *= -1;
}
box.style.left = l + a + "px";
var t = box.offsetTop;
if(t == h || t == 0){
b *= -1;
}
box.style.top = t + b + "px";
},10);
</script>
</body>
</html>