jQuery飘动广告是一种常见的网页特效,它可以使广告元素在页面上浮动,吸引用户的注意力。下面是一个简单的jQuery飘动广告代码示例:
飘动广告通常使用CSS和JavaScript(或jQuery)来实现。通过设置元素的定位和动画效果,使其在页面上移动。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Floating Ad Example</title>
<style>
#floatingAd {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
color: white;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div id="floatingAd">广告</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var ad = $('#floatingAd');
var adWidth = ad.outerWidth(true);
var adHeight = ad.outerHeight(true);
var windowWidth = $(window).width();
var windowHeight = $(window).height();
var x = windowWidth + adWidth;
var y = Math.floor(Math.random() * (windowHeight - adHeight));
ad.css({
left: x + 'px',
top: y + 'px'
});
var directionX = -1;
var directionY = 1;
var speed = 1;
function moveAd() {
x += directionX * speed;
y += directionY * speed;
if (x + adWidth < 0) {
x = windowWidth;
}
if (y < 0 || y + adHeight > windowHeight) {
directionY = -directionY;
}
ad.css({
left: x + 'px',
top: y + 'px'
});
setTimeout(moveAd, 20);
}
moveAd();
});
</script>
</body>
</html>
requestAnimationFrame
代替setTimeout
。通过以上代码和解释,你应该能够实现一个基本的jQuery飘动广告,并了解其相关概念和应用场景。
领取专属 10元无门槛券
手把手带您无忧上云