简体   繁体   English

使用jQuery,如何根据页面高度限制广告单元的数量?

[英]Using jQuery, how can I limit my number of ad units based on page height?

My app is built using a 2-column design, with the right 300-pixel column being used to show one Adsense ad unit. 我的应用是使用2列设计构建的,右边的300像素列用于显示一个 Adsense广告单元。

Since some pages are taller, I am wondering if there's a way to have jQuery determine the height of my #main_wrapper and show an additional ad unit if it exceeds a certain size in pixels. 由于某些页面更高,我想知道是否有一种方法可以让jQuery确定我的#main_wrapper的高度,并在其超出某个像素大小的情况下显示另一个广告单元 Sort of like this: 有点像这样:

    // ad unit #1 shown here by default in all pages

<script>

$(document).ready(function(){

            if ($('#main_wrapper').height() > 660) {

            //show add unit #2
        }

});

</script>

My issue is with how to deal with wrapping the ad unit code with the jQuery/JS condition above. 我的问题是如何使用上述jQuery / JS条件包装广告单元代码。 A typical ad unit is: 典型的广告单元是:

<script type="text/javascript"><!--
google_ad_client = "ca-pub-123123123123";
/* Sidebar 300 Middle */
google_ad_slot = "123123123";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

How would I insert that inside the jQuery above? 我如何将其插入上面的jQuery中?

Maybe you should include this strings in the needed block? 也许您应该在所需的块中包含此字符串?

 if ($('#main_wrapper').height() > 660)
 {
  google_ad_client = "ca-pub-123123123123";
  google_ad_slot = "123123123";
  google_ad_width = 300;
  google_ad_height = 250;
 }

Something like: 就像是:

Edit: Code changed as previous was causing error parsing </script> 编辑:更改为以前的代码会导致错误解析</script>

Edit: After reading this replaced jquery's .append() with pojs and script element is being added to DOM tree 编辑:阅读替换的jquery的.append()与pojs和脚本元素被添加到DOM树

$(document).ready(function(){

    function adUnit(client, slot, width, height) {
        var unit = '<!--\n';
            unit += 'google_ad_client = ' + client + ';\n';
            unit += 'google_ad_slot = ' + slot + ';\n';
            unit += 'google_ad_width = ' + width + ';\n';
            unit += 'google_ad_height = ' + height + ';\n';
            unit += '//-->';

        var script = document.createElement('script');
            script.type = 'text/javascript';
            script.text =  unit;

        document.head.appendChild(script);
        console.log('adUnit executed');
    }
    adUnit(1, 2, 3, 4);

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM