您当前的位置:首页 > 计算机 > 服务器 > 万维网站 > 网站优化

简单代码实现网页左右侧的广告悬浮效果

时间:10-26来源:作者:点击数:

罗列出四个简便的步骤,即可实现两侧悬浮广告效果,广告宽高可调节。通过我亲自试错,得出最终的 JavaScript 简单算法策略,使左右两侧广告的悬浮效果完美的呈现。

一、引入adsbygoogle.js

只需要引入一次 adsbygoogle.js 就够了。

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

二、HTML

两个 div 分别为左侧悬浮和右侧悬浮

  • left: 10px;左留宽10px(可调)
  • top: 80px头;高度预留80px(可调)
  • max-width: 230px;此宽为推荐参数,广告单元最大宽度230px(可调)
<div id="left-ad" style="position: fixed;left: 10px;top: 80px;width: 100%;max-width: 230px;"></div>
<div id="right-ad" style="position: fixed;right: 10px;top: 80px;width: 100%;max-width: 230px;"></div>

!!如有需求可在网页底部加入第三块广告单元。

<div class="www-catyoads">
    <!--www-catyoads-->
    <ins class="adsbygoogle"
        style="display:block; text-align:center;"
        data-ad-layout="in-article"
        data-ad-format="fluid"
        data-ad-client="ca-pub-3xxxxxxxxxxxxxx0"
        data-ad-slot="8xxxxxxxx5"></ins>
    <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
</div>

三、CSS

用 CSS 控制广告显示或隐藏,判断窗口宽度小于 1366px 后隐藏左右两侧的 div,效果为 PC 端为显示两侧广告,移动端通常则隐藏两侧广告单元,避免 ad­sense 破坏排版。

max-width 根据中心区内容宽度来自定义参数。

@media screen and (max-width: 1366px) {
    #left-ad,#right-ad{
        display: none;
    }
}

四、JavaScript判断

在此之前,要先拿到 Google Ad­Sense 中现有的广告单元代码,只需要拷贝下面参考实例中的 ins 部分就行。

ins部分
ins部分

步入正题,判断窗口宽度大于 1366px 后在左右两侧 div 中插入广告单元代码。加入此判断和通过 js 插入广告单元代码,是为避免在缩放到小于 1366px 后出现 adsbygoogle push 异常的情况。

if (window.innerWidth > 1366) {
    // 左侧广告单元代码
    var left_ad = '<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3xxxxxxxxxxxxxx0" data-ad-slot="5xxxxxxxx7" data-ad-format="auto" data-full-width-responsive="true"></ins>';
    $("#left-ad").append(left_ad);
    (adsbygoogle = window.adsbygoogle || []).push({});

    // 右侧广告单元代码
    var right_ad = '<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3xxxxxxxxxxxxxx0" data-ad-slot="1xxxxxxxx9" data-ad-format="auto" data-full-width-responsive="true"></ins>';
    $("#right-ad").append(right_ad);
    (adsbygoogle = window.adsbygoogle || []).push({});
} else {
    // 清空左右两侧广告div中的内容
    $("#left-ad").html("");
    $("#right-ad").html("");
}

效果展示

  • 猫鼬工作室官网:www.catyo.cn ⬅
猫鼬工作室官网的广告效果.gif
猫鼬工作室官网的广告效果.gif

  • 棱镜计划导航页:prism.catyo.cn ⬅
棱镜计划的广告效果.jpg
棱镜计划的广告效果.jpg

  • 猫鼬API导航页:api.catyo.cn ⬅
猫鼬API的广告效果.jpg
猫鼬API的广告效果.jpg
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门