罗列出四个简便的步骤,即可实现两侧悬浮广告效果,广告宽高可调节。通过我亲自试错,得出最终的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端为显示两侧广告,移动端通常则隐藏两侧广告单元,避免adsense破坏排版。
max-width
根据中心区内容宽度来自定义参数。
@media screen and (max-width: 1366px) {
#left-ad,#right-ad{
display: none;
}
}
四、JavaScript判断
在此之前,要先拿到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("");
}
效果展示
- 猫鼬工作室官网:www.catyo.cn ⬅
- 棱镜计划导航页:prism.catyo.cn ⬅
- 猫鼬API导航页:api.catyo.cn ⬅
本文作者:Catyo
本文链接:https://blog.catyo.cn/archives/1434/
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。非商业转载及引用请注明出处(作者、原文链接),商业转载请联系作者获得授权。
收藏评论一气呵成
大佬我惊呆了!人愣了一下

哈哈哈,捕捉一枚老司机
老司机
到点了,上号开冲
有种对联的感觉
底部的摆到上面话,就成三副对联啦
悄悄话:
评论区支持MD语法了喔,欢迎来玩!