【问题标题】:Hide div if it only contains <script> tags如果 div 仅包含 <script> 标签,则隐藏它
【发布时间】:2018-10-06 07:01:59
【问题描述】:

与这个 6 年前的问题类似,但我没有查看父元素并想知道是否有更好的解决方案? hide div (it contains only script tag)

问题: 我的网站有一些用于 google adsense 广告的块。这些块只是样式化的 div(背景颜色、填充、边距、边框半径等)。除了 adsense 脚本标签(当然还有空白/文本节点等)之外,它们什么都没有。当用户有一个广告块扩展/插件时,这些 div 仍然显示,但它们在屏幕上看起来完全是空的,这是不可取的。因此,如果没有呈现广告,我正在寻找一种隐藏这些 div 的方法。使用:empty 或不起作用,因为它仍然会拾取&lt;script&gt; 标签。

Div 元素:

<div class="contentBlock"><script>//adsense code</script></div>

也许有更好的方法来解决或概念化这个问题?如果是这样,我愿意接受替代解决方案。谢谢!

【问题讨论】:

  • 脚本标签必须进入 div 有什么原因吗?
  • @Deadron - 这就是广告脚本通常的工作方式。他们使用document.write 做他们的事情,因此广告会出现在页面作者希望它出现的位置。
  • 每个ad 内容的类总是contentBlock 吗?

标签: javascript jquery html css


【解决方案1】:

您可以删除script 标签,然后检查块是否为空。在之后运行的代码中,如果允许,广告代码将会运行:

var blocks = $(".contentBlock");
blocks.find("script").remove();
blocks.each(function() {
    var div = $(this);
    if (!div.html().trim()) {
        div.remove();
    }
});

或者如果你喜欢链接很多:

$(".contentBlock")
    .find("script")
    .remove()
    .end()
    .each(function() {
        var div = $(this);
        if (!div.html().trim()) {
            div.remove();
        }
    });

如果您必须支持过时的浏览器,请使用 $.trim() 而不是原生的 String.prototype.trim(或 polyfill)。

【讨论】:

    【解决方案2】:

    您似乎需要 CSS4 建议列表中的一项功能:https://www.w3.org/TR/selectors-4/#has-pseudo

    关系伪类:has()是一个函数伪类 将相对选择器列表作为参数。它代表一个 元素,如果有任何相对选择器,当绝对化和 使用元素作为 :scope 元素进行评估,将匹配 至少一个元素。 ...

    以下选择器匹配不包含任何标题元素的元素:

    section:not(:has(h1, h2, h3, h4, h5, h6))

    另一种解决方法是使用 jquery 用内容标记 div,然后删除/隐藏其他内容。见小提琴:http://jsfiddle.net/mczv6gys/

    $('div.contentBlock').has('p, span, img, div').addClass('markerClass'); // P or any other typical tag
    $('div.contentBlock').not('.markerClass').addClass('hideClass'); // eg display:none
    

    【讨论】:

      【解决方案3】:

      您可以隐藏 div,或者如果 AdSense 隐藏了内容,则将其替换为新内容。

      如果此示例不起作用,您将需要处理从 Adsense 动态创建的内容。例如检查$("#google_ads_frame1").css('display')=="none")。而不是检查您的容器 div。哪个可行,已经过测试。

      • 您将内容包装到容器/div 中 广告。然后设置一个超时函数来确定说 问题。如果启用了广告拦截,则显示替代内容,例如 视频、海报、iframe 等。
      • 由于 adblock 也使用 css 隐藏内容,因此您可以将 css 编辑为 如果启用而不是替换,最终隐藏所有内容。二 选项。

      将 sn-p 超时更改为您要等待检查的任何时间 页面加载后,处理异步广告。

      // Page has loaded
            window.onload = function(){ 
              // Set a timeout function for async google ads
              setTimeout(function() { 
                // We are targeting the first banner ad of AdSense
                var ad = document.querySelector(".ads");
                // If the ad contains no innerHTML, adblock is enabled
                // Or check adsense's generated content 
                // $("#google_ads_frame1").css('display')=="none")
                if (ad && ad.innerHTML.replace(/\s/g, "").length == 0) {
                  // Adblock hides with css also, or just hide everything.
                  ad.style.cssText = 'display:block !important; background-color: LightCoral;'; 
                  // Replace, if adblock enabled
                  ad.innerHTML = 'We detected adblock';
                }
              }, 1); // Change this to 2000 to run after two seconds, to handle async ads
            }; 
      .ads {
        background-color: lightgreen;
      }
      <p><b>Example 1:</b> Let us simulate an adblock situation, the <code>script</code> tag did not load, hence adblock</p>
      
      <div class="ads"></div>
      
      <p><b>Example 2:</b> Let us simulate no adblock, <code>script</code> tag loaded</p>
      
      <div class="ads"><script></script>Adblock ran</div>

      【讨论】:

        【解决方案4】:

        如果你支持ES6特性,你可以过滤.contentBlock,每个节点满足条件是“空”的textNode,是Script还是comment:

        let emptyBlocks = [...document.querySelectorAll('.contentBlock')].filter(block =>
          [...block.childNodes].every(node =>
            (node.nodeName === '#text') ?
               !node.textContent.trim(): 
               ['SCRIPT','#comment'].includes(node.nodeName)
          )
        );
        
        
        
        emptyBlocks.forEach(function(block){
          block.classList.add('empty');  
        });
        .contentBlock{
          min-height:50px;
          width:200px;
          outline: solid 2px red;
          margin:2px;
        }
        
        .contentBlock.empty{
          display: none;
        }
        <div class="contentBlock">
          <script>//nothing's happened</script><!--comment-->
        </div>
        
        <div class="contentBlock">
          <script>document.write('something\'s happened');</script>
        </div>
        
        <div class="contentBlock">
          <!--comment-->
          <script></script>
        <!-- empty text nodes with spaces and tabulations -->
        
                  
        
        
        </div>
        
        <div class="contentBlock">
        <!--//-->
        text node
        </div>

        【讨论】:

          猜你喜欢
          • 2012-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多