如何在窗口大小调整时使用Jquery在DOM中添加/删除Div

时间:2014-08-21 12:21:58

标签: javascript jquery dom

我正在尝试删除并在窗口调整大小时将div添加回DOm。

我在移动网页上生成了两个不同的position谷歌添加。根据谷歌政策,移动页面只能添加一个。

但是我必须根据不同的窗口大小/移动设备等显示谷歌添加到diffenret的地方。所以我只是使用Media QUeries隐藏其中一个。

但是,由于另一个div也在dom中,它违反了政策。所以我使用了以下脚本

<script>
$(document).on('pagecreate','#outerPage',function(e) {
   var windowWidth = $(this).width();
   if(windowWidth <300)
   {
       $('.addBigphone').remove();
   }
   else
   {
       $('.addSmallphone').remove();
   }
});
</script>

html看起来像这样

<div id="bloque" class="addSmallphone">
    <?php // if($showadslast==t rue){?>
    <div class="google_add">
        <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        <!-- resultmobile -->
<ins class="adsbygoogle" style="display:inline-block;width:320px;height:90px" data-ad-client="ca-pub-8" data-ad-slot=""></ins>

        <script>
            (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
    </div>

<div id="bloque1" class="addBigphone">
        <?php // if($showadslast==t rue){?>
        <div class="google_add">
            <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
            <!-- resultmobile -->
    <ins class="adsbygoogle" style="display:inline-block;width:320px;height:90px" data-ad-client="ca-pub-8" data-ad-slot="04"></ins>

            <script>
                (adsbygoogle = window.adsbygoogle || []).push({});
            </script>
        </div>

现在它仅适用于页面加载。

注意我想保存div的内容并将其添加回不同的调整大小。我怎么能这样做

提前致谢

2 个答案:

答案 0 :(得分:1)

听起来你应该使用resize事件。

jquery http://api.jquery.com/resize/

您可以在调整大小时检测窗口大小,存储所需的任何数据,并在窗口大小更改时采取措施。

答案 1 :(得分:1)

我认为这就是你想要的。当您计划在DOM中重新插入元素时,应该使用detach而不是remove

var $bigPhoneAdd = $('.addBigphone'),
    $smallPhoneAdd = $('.addSmallphone');

$(window).resize(function(e) {
   var windowWidth = $(this).width();

   if (windowWidth < 300) {
       $bigPhoneAdd.detach();

       //You should append at desired insertion point...
       //Perhaps it could be made dynamic by storing $('.addBigphone').parent()
       //when the page loaded.
       $smallPhoneAdd.appendTo(?);
   }
   else {
       $smallPhoneAdd.detach();

       //You should append at desired insertion point...
       $bigPhoneAdd.appendTo(?);
   }
});
相关问题