今天给大家介绍下做的一个随机飘动的广告:
预览效果图

效果图.gif
第一步 :需要导入
<script src="./js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
第二步: HTML代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="./js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="css/gg.js" type="text/javascript" charset="utf-8"></script>
</head>
<body style="width: 2000px; height: 2000px; background-color: rgba(123,125,125,0.2);">
<div style=" text-align:center; 150px; height: 150px; background-color: rgba(120,0,0,0.5); border: 2px solid #222222; box-shadow: 0 0 15px #000000; border-radius: 5px;">
招生热线<br />
QQ:xxxxxxxxx <br />
tel:xxxxxxxxx<br />
tel0731-xxxxxxxxx<br />
湖南软件职业学院
</div>
<div style=" text-align:center; 150px; height: 150px; background-color: rgba(120,190,0,0.5); border: 2px solid #222222; box-shadow: 0 0 15px #000000; border-radius: 5px;">
招生热线<br />
QQ:1615278696 <br />
tel:15197960780<br />
tel0731-4451273<br />
湖南软件职业学院
</div>
<div style=" text-align:center; 150px; height: 150px; background-color: rgba(120,0,0,0.5); border: 2px solid #222222; box-shadow: 0 0 15px #000000; border-radius: 5px;">
招生热线<br />
QQ:xxxxxxxxx <br />
tel:xxxxxxxxx<br />
tel0731-xxxxxxxxx<br />
湖南软件职业学院
</div>
<div style=" text-align:center; 150px; height: 150px; background-color: rgba(120,240,0,0.5); border: 2px solid #222222; box-shadow: 0 0 15px #000000; border-radius: 5px;">
招生热线<br />
QQ:xxxxxxxxx <br />
tel:xxxxxxxxx<br />
tel0731-xxxxxxxxx<br />
湖南软件职业学院
</div>
<div style=" text-align:center; 150px; height: 150px; background-color: rgba(120,0,230,0.5); border: 2px solid #222222; box-shadow: 0 0 15px #000000; border-radius: 5px;">
招生热线<br />
QQ:xxxxxxxxx <br />
tel:xxxxxxxxx<br />
tel0731-xxxxxxxxx<br />
湖南软件职业学院
</div>
</body>
</html>
第三步 js代码
function ad1(adObj) {
let obj = $(adObj);
console.info(obj);
obj.css("position", "fixed");
let maxWidth, maxHeight;
$(window).resize(function() {
maxWidth = $(window).width() - obj.outerWidth();
maxHeight = $(window).height() - obj.outerHeight();
}).resize();
let xy = {top: Math.random() * maxHeight, left: Math.random() * maxWidth};
obj.offset(xy);
let speed = {top: 1,left: 10};
let count = 20 + Math.random()*30;
window.setInterval(function() {
--count;
if (count < 0) {
speed.left = Math.random() * 20 - 10;
speed.top = Math.random() * 20 - 10;
count = 20 + Math.random() * 30;
}
xy.left += speed.left;
if (xy.left > maxWidth) {
xy.left = maxWidth;
speed.left = -speed.left;
} else if (xy.left < 0) {
xy.left = 0;
speed.left = -speed.left;
}
xy.top += speed.top;
if (xy.top > maxHeight) {
xy.top = maxHeight;
speed.top = -speed.top;
} else if (xy.top < 0) {
xy.top = 0;
speed.top = -speed.top;
}
obj.offset(xy);
}, 100);
}
$.fn.add=function(){
console.info(this);
$(this).each(function(i,v){
ad1(v);
});
}
$(function() {
var obj = $("div");
obj.add();
});
```