简体   繁体   English

如果仅包含div,则将其隐藏<script> tags

[英]Hide div if it only contains <script> tags

Similar to this 6-year old question, but I'm not looking at parent elements and wondering if there is a better solution? 类似于这个已有6年历史的问题,但是我没有考虑父元素,并且想知道是否有更好的解决方案? hide div (it contains only script tag) 隐藏div(仅包含脚本标签)

Question: My website has some blocks for google adsense advertisements. 问题:我的网站对Google adsense广告有一些限制。 These blocks are just styled divs (background color, padding, margin, border-radius etc.) There is nothing in them except for the adsense script tags (and of course white space/text nodes, etc.). 这些块只是样式化的div(背景颜色,填充,边距,边界半径等)。除了adsense脚本标签(当然还有空白/文本节点等)之外,其中没有任何内容。 When a user has an ad block extension/plug-in, these divs still display, but they appear totally empty on the screen, which is not desirable. 当用户使用广告块扩展程序/插件时,这些div仍会显示,但它们在屏幕上显得完全空白,这是不希望的。 Therefore, I'm looking for a way to hide these divs if no ad is rendered. 因此,如果没有广告呈现,我正在寻找一种隐藏这些div的方法。 Using :empty or does not work since it still picks up the <script> tags. 使用:empty还是不起作用,因为它仍然会拾取<script>标记。

Div element: Div元素:

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

Perhaps there is a better way of tackling or conceptualizing this problem? 也许有更好的方法来解决或概念化此问题? If so, I'm open to alternative solutions. 如果是这样,我愿意接受其他解决方案。 Thanks! 谢谢!

You can remove the script tags, and then check to see if the blocks are empty. 您可以删除script标签,然后检查块是否为空。 In code that runs after the ad code would run if it were allowed to: 如果允许,则广告代码之后投放的代码中:

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

Or if you like chaining a lot: 或者,如果您喜欢链接很多:

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

If you have to support obsolete browsers, use $.trim() instead of the native String.prototype.trim (or polyfill it). 如果您必须支持过时的浏览器,请使用$.trim()而不是本机的String.prototype.trim (或对其进行$.trim() )。

It seems that you need a feature which is on CSS4 proposed list: https://www.w3.org/TR/selectors-4/#has-pseudo 似乎您需要CSS4建议列表中的功能: https : //www.w3.org/TR/selectors-4/#has-pseudo

The relational pseudo-class, :has(), is a functional pseudo-class taking a relative selector list as an argument. 关系伪类:has()是一个功能性伪类,以相对选择器列表作为参数。 It represents an element if any of the relative selectors, when absolutized and evaluated with the element as the :scope elements, would match at least one element. 如果某个相对选择器的绝对值和以:scope元素评估的相对选择器中的至少一个匹配,则它表示元素。 ... ...

The following selector matches elements that don't contain any heading elements: 以下选择器匹配不包含任何标题元素的元素:

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

Another workaround is to use jquery to mark divs with content and then remove/hide the others. 另一个解决方法是使用jquery将div标记为内容,然后删除/隐藏其他内容。 See fiddle: http://jsfiddle.net/mczv6gys/ 参见小提琴: 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

You have the ability to either hide the div, or replace it with new content if AdSense hides the content. 您可以隐藏div,如果AdSense隐藏了该内容,则可以将其替换为新内容。

If this example isn't working, your going to want to deal with the content dynamically created from Adsense. 如果此示例不起作用,您将要处理从Adsense动态创建的内容。 Such as a check for $("#google_ads_frame1").css('display')=="none") . 例如检查$("#google_ads_frame1").css('display')=="none") Instead of checking your container div. 而不是检查您的容器div。 Which would work, it was tested. 哪个可行,已经过测试。

  • You wrap your content into a container / div for strictly advertisements. 您将内容包装到容器/ div中以进行严格的广告宣传。 Then set a timeout function to determined said issues. 然后设置一个超时功能来确定所述问题。 If adblock enabled, then show alternative content such as a video, poster, iframe, etc. 如果启用了adblock,则显示其他内容,例如视频,海报,iframe等。
  • Since adblock hides stuff with css too, you can then edit the css to ultimately hide everything if enabled instead of replacing. 由于adblock也会用CSS隐藏东西,因此您可以编辑CSS以最终隐藏所有东西(如果启用)而不是替换。 Two options. 两种选择。

Change snippet timeout to whatever time you want to wait to check after page loaded, to handle async ads. 将代码段超时更改为您希望在页面加载后等待检查的任何时间,以处理异步广告。

 // 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> 

If you support ES6 features, you can filter .contentBlock which every nodes satisfy condition is "empty" textNode, is Script or is comment: 如果支持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> 

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

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