下面是基于JS实现弹性漂浮广告的完整攻略:
position: fixed
实现元素的固定位置,定义元素距离浏览器顶部的距离。setInterval
来实现广告元素的动态滚动。定义广告元素的样式。
.floating-ad {
position: fixed;
top: 30%;
left: 0;
width: 100%;
text-align: center;
z-index: 99999;
display: none; /* 初始隐藏广告 */
}
setInterval
函数设置定时器,定义广告元素的滚动速度和容器宽度。示例1:最简单的实现方案
// 获取广告元素以及定义最大宽度、高度
const ad = document.querySelector('.floating-ad');
const maxWidth = 600;
const maxHeight = 300;
// 定义广告元素滚动速度(px/s)和容器宽度
let speed = 100;
let containerWidth = document.body.clientWidth;
// 设置定时器,实现广告元素的滚动效果
setInterval(() => {
let adWidth = ad.clientWidth;
let adHeight = ad.clientHeight;
// 当广告元素超过最大宽度或高度时,重置广告元素的大小和位置
if (adWidth > maxWidth || adHeight > maxHeight) {
ad.style.width = maxWidth + 'px';
ad.style.height = maxHeight + 'px';
ad.style.top = '30%';
ad.style.left = (containerWidth - maxWidth) / 2 + 'px';
}
// 计算广告元素新的left值,并更新广告元素的位置
let newLeft = parseFloat(ad.style.left) + speed / 100;
if (newLeft >= containerWidth - adWidth) {
newLeft = containerWidth - adWidth;
speed = -speed;
}
if (newLeft <= 0) {
newLeft = 0;
speed = -speed;
}
ad.style.left = newLeft + 'px';
}, 16);
// 监听窗口大小变化,动态调整广告元素的位置和大小
window.addEventListener('resize', () => {
containerWidth = document.body.clientWidth;
ad.style.left = (containerWidth - ad.clientWidth) / 2 + 'px';
ad.style.top = '30%';
});
// 监听鼠标滚轮事件,实现广告元素的动态显示和隐藏
let lastScrollTop = 0;
window.addEventListener('scroll', () => {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if (scrollTop > lastScrollTop) {
ad.style.display = 'none';
} else {
ad.style.display = 'block';
}
lastScrollTop = scrollTop;
});
示例2:结合jQuery实现更加简洁优雅的代码
$(function() {
const ad = $('.floating-ad');
const maxWidth = 600;
const maxHeight = 300;
let speed = 100;
let containerWidth = $(window).width();
setInterval(() => {
if (ad.width() > maxWidth || ad.height() > maxHeight) {
ad.width(maxWidth).height(maxHeight).css({
top: '30%',
left: (containerWidth - maxWidth) / 2
});
}
let newLeft = parseFloat(ad.css('left')) + speed / 100;
if (newLeft >= containerWidth - ad.width()) {
newLeft = containerWidth - ad.width();
speed = -speed;
}
if (newLeft <= 0) {
newLeft = 0;
speed = -speed;
}
ad.css('left', newLeft);
}, 16);
$(window).on('resize', () => {
containerWidth = $(window).width();
ad.css('left', (containerWidth - ad.width()) / 2).css('top', '30%');
});
let lastScrollTop = 0;
$(window).on('scroll', () => {
let scrollTop = $(window).scrollTop();
if (scrollTop > lastScrollTop) {
ad.hide();
} else {
ad.show();
}
lastScrollTop = scrollTop;
});
});
本文链接:http://task.lmcjl.com/news/9277.html