罗列出四个简便的步骤,即可实现两侧悬浮广告效果,广告宽高可调节。通过我亲自试错,得出最终的 JavaScript 简单算法策略,使左右两侧广告的悬浮效果完美的呈现。
只需要引入一次 adsbygoogle.js 就够了。
- <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
两个 div 分别为左侧悬浮和右侧悬浮。
- <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 控制广告显示或隐藏,判断窗口宽度小于 1366px 后隐藏左右两侧的 div,效果为 PC 端为显示两侧广告,移动端通常则隐藏两侧广告单元,避免 adsense 破坏排版。
max-width 根据中心区内容宽度来自定义参数。
- @media screen and (max-width: 1366px) {
- #left-ad,#right-ad{
- display: none;
- }
- }
在此之前,要先拿到 Google AdSense 中现有的广告单元代码,只需要拷贝下面参考实例中的 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("");
- }