簡體   English   中英

如何在窗口調整大小時使用Jquery從DOM中添加/刪除Div

[英]How to add/remove Div from the DOM using Jquery on window resize

我正在嘗試刪除div並將其添加回窗口調整大小的DOm上。

我在移動網頁的不同position生成了兩個google add。 根據Google的政策,移動頁只能添加一個。

但是我不得不顯示谷歌根據不同的窗口大小/移動設備等在diffenret的地方添加。 所以我只是使用Media QUeries隱藏其中一個。

但是由於另一個div也處於管轄區,因此違反了政策。 所以我用下面的腳本

<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的內容,並以不同的大小將其重新添加。 我怎樣才能做到這一點

提前致謝

聽起來您應該使用resize事件。

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

您可以在調整大小時檢測窗口的大小,存儲所需的任何數據,並在窗口大小更改時采取措施。

我想這就是你想要的。 當您計划在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(?);
   }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM