下面我将为你提供一个完整的、可运行的示例,并详细解释其工作原理,最后还会提供一些可定制的选项和优化建议。

网页上随意飘动的广告jquery
(图片来源网络,侵删)

最终效果预览


第一步:准备 HTML 结构

我们需要在 HTML 中放置广告元素,这个广告会是一个绝对定位的 div,并包含一个关闭按钮。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">飘动广告示例</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>页面内容,向下滚动查看效果</h1>
    <p>这里是页面的主要内容,为了演示,这里放置了很多占位符文本。</p>
    <!-- 为了演示滚动效果,这里添加很多占位内容 -->
    <div style="height: 2000px; background: #f0f0f0; text-align: center; line-height: 2000px;">
        我是页面底部
    </div>
    <!-- 飘动广告的 HTML 结构 -->
    <div id="floating-ad">
        <img src="https://via.placeholder.com/200x150.png?text=AD" alt="广告图片">
        <span class="close-btn">×</span>
    </div>
    <!-- 引入 jQuery 库 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

代码解释:

  1. <div id="floating-ad">: 这是广告的容器,我们给它一个唯一的 ID,方便 jQuery 选中它。
  2. <img>: 广告的具体内容,这里用一张占位图片代替。
  3. <span class="close-btn">: 关闭按钮,让用户可以手动关闭广告。
  4. <script>: 引入 jQuery 库和我们自己编写的 JavaScript 文件。

第二步:编写 CSS 样式

为了让广告能够浮动并看起来美观,我们需要用 CSS 来设置它的样式。

/* style.css */
body {
    font-family: sans-serif;
    margin: 0;
    padding: 0;
}
/* 广告容器的初始样式 */
#floating-ad {
    position: absolute; /* 关键:脱离文档流,便于定位 */
    width: 200px;
    border: 2px solid #ccc;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    cursor: move; /* 鼠标悬停时显示为可移动状态 */
    z-index: 1000; /* 确保广告在页面内容之上 */
    background-color: white;
}
/* 广告图片样式 */
#floating-ad img {
    display: block;
    width: 100%;
    height: auto;
    border-radius: 8px 8px 0 0;
}
/* 关闭按钮样式 */
.close-btn {
    position: absolute;
    top: -10px;
    right: -10px;
    width: 24px;
    height: 24px;
    background-color: #ff4444;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 24px;
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    border: 2px solid white;
}
.close-btn:hover {
    background-color: #cc0000;
}

CSS 关键点:

网页上随意飘动的广告jquery
(图片来源网络,侵删)
  1. position: absolute;: 这是实现飘动效果的核心,它将广告从正常的文档流中脱离出来,我们可以通过 topleft 属性来精确控制它的位置。
  2. z-index: 1000;: 设置一个较高的层级,确保广告不会被页面上的其他元素遮挡。
  3. cursor: move;: 鼠标移到广告上时,光标变成可移动的样式,提升用户体验。
  4. .close-btn: 关闭按钮使用 position: absolute; 定位在广告的右上角,并添加了圆形背景和悬停效果。

第三步:编写 jQuery (JavaScript) 逻辑

这是实现“随意飘动”功能的核心部分,我们将使用 jQuery 来动态改变广告的位置。

// script.js
$(document).ready(function() {
    // 1. 获取广告元素
    const $ad = $('#floating-ad');
    // 2. 定义变量
    let x = 20; // 初始 left 位置
    let y = 20; // 初始 top 位置
    let dx = 1; // x轴移动速度
    let dy = 1; // y轴移动速度
    let intervalId; // 用于存储定时器的ID
    // 3. 创建飘动函数
    function floatAd() {
        // 获取浏览器窗口的宽高
        const windowWidth = $(window).width();
        const windowHeight = $(window).height();
        const adWidth = $ad.outerWidth();
        const adHeight = $ad.outerHeight();
        // 检查是否碰到左右边界
        if (x + adWidth >= windowWidth || x <= 0) {
            dx = -dx; // 反转x轴方向
        }
        // 检查是否碰到上下边界
        if (y + adHeight >= windowHeight || y <= 0) {
            dy = -dy; // 反转y轴方向
        }
        // 更新广告的位置
        x += dx;
        y += dy;
        // 将新的位置应用到广告元素上
        $ad.css({
            'left': x + 'px',
            'top': y + 'px'
        });
    }
    // 4. 启动飘动 (每30毫秒移动一次)
    intervalId = setInterval(floatAd, 30);
    // 5. 实现拖拽功能
    let isDragging = false;
    let offset = { x: 0, y: 0 };
    $ad.on('mousedown', function(e) {
        // 停止自动飘动
        clearInterval(intervalId);
        isDragging = true;
        // 计算鼠标相对于广告元素左上角的偏移
        offset.x = e.pageX - $ad.offset().left;
        offset.y = e.pageY - $ad.offset().top;
        // 防止文本选中
        $ad.css('user-select', 'none');
    });
    $(document).on('mousemove', function(e) {
        if (isDragging) {
            // 计算广告的新位置
            x = e.pageX - offset.x;
            y = e.pageY - offset.y;
            // 限制广告在窗口内
            x = Math.max(0, Math.min(x, $(window).width() - $ad.outerWidth()));
            y = Math.max(0, Math.min(y, $(window).height() - $ad.outerHeight()));
            // 更新广告位置
            $ad.css({
                'left': x + 'px',
                'top': y + 'px'
            });
        }
    }).on('mouseup', function() {
        if (isDragging) {
            isDragging = false;
            // 恢复自动飘动
            intervalId = setInterval(floatAd, 30);
            // 恢复文本选中
            $ad.css('user-select', 'text');
        }
    });
    // 6. 实现关闭功能
    $('.close-btn').on('click', function() {
        // 停止定时器,停止动画
        clearInterval(intervalId);
        // 隐藏广告
        $ad.fadeOut(300);
    });
});

JavaScript 逻辑详解:

  1. 变量定义:

    • x, y: 记录广告当前的坐标。
    • dx, dy: 控制广告在 x 轴和 y 轴上的移动方向和速度,每次 floatAd 函数执行时,xy 就会增加 dxdy 的值。
    • intervalId: 保存 setInterval 返回的 ID,以便之后可以清除定时器,停止飘动。
  2. floatAd 函数:

    网页上随意飘动的广告jquery
    (图片来源网络,侵删)
    • 这是飘动的核心逻辑,它首先获取窗口和广告的尺寸。
    • 然后通过 if 语句判断广告是否碰到了窗口的边界,如果碰到了,就将相应的速度分量(dxdy)取反,这样广告就会“反弹”。
    • 更新 xy 的值,并使用 $ad.css() 将新的位置应用到广告元素上。
  3. setInterval:

    • setInterval(floatAd, 30) 的意思是:每隔 30 毫秒就调用一次 floatAd 函数,这个数值越小,广告移动得越快、越平滑。
  4. 拖拽功能:

    • mousedown: 当用户在广告上按下鼠标时,我们停止自动飘动(clearInterval),并记录下鼠标点击位置与广告左上角的偏移量,这个偏移量很重要,它保证了拖动时广告不会“跳”到鼠标的中心位置。
    • mousemove: 当鼠标在页面上移动时,isDraggingtrue(表示正在拖动),我们就根据鼠标的当前位置和之前记录的偏移量,计算出广告的新位置,并更新它,这里还添加了边界限制,防止广告被拖出窗口。
    • mouseup: 当用户松开鼠标时,isDragging 设为 false,并重新启动飘动动画。
  5. 关闭功能:

    • 点击关闭按钮时,我们同样先清除定时器,然后使用 $ad.fadeOut(300) 让广告以一个淡出的效果消失。fadeOut 比直接 hide()display: none; 视觉上更友好。

可定制选项与优化

  • 调整速度: 修改 setInterval 的第二个参数,数值越小越快。setInterval(floatAd, 20) 会比 30 更快。
  • 调整移动方向: 修改 dxdy 的初始值。let dx = 2; 会让广告在 x 轴上移动得更快。let dy = -1; 会让广告一开始就向上移动。
  • 改变反弹方式: 目前的反弹是硬碰硬的,你可以让它碰到边界后从另一边出现(类似贪吃蛇)。
    // 在 floatAd 函数中替换反弹逻辑
    if (x + adWidth >= windowWidth) {
        x = 0; // 从左边出现
    } else if (x <= 0) {
        x = windowWidth - adWidth; // 从右边出现
    }
  • 性能优化: 对于非常复杂的动画,可以考虑使用 CSS3 的 transform: translate(x, y) 属性来改变位置,因为它可以利用 GPU 加速,性能通常比直接修改 lefttop 更好。
    // 在 floatAd 函数最后,将
    $ad.css({
        'left': x + 'px',
        'top': y + 'px'
    });
    // 替换为
    $ad.css('transform', `translate(${x}px, ${y}px)`);

    注意: 如果使用 transform,广告的初始位置需要通过 CSS 的 transform 来设置,或者确保 lefttop 为 0。

这个示例提供了一个功能完整、用户体验良好的飘动广告,你可以根据你的具体需求进行修改和扩展。