简体   繁体   English

如何使用 JavaScript(包括 CSS 和 img)计算页面上的所有图像

[英]How can count all images on a page with JavaScript (including CSS and img)

It's trivial to get the <img> elements on a page with JavaScript:使用 JavaScript 在页面上获取<img>元素很简单:

  • document.images
  • document.getElementsByTagName('img')

But is there a (reasonably easy) way to get all images loaded on the page?但是有没有一种(相当简单的)方法可以让所有图像加载到页面上?

I've considered looping through all elements using querySelectorAll('*') and checking their style.background and style.backgroundImage properties for url , then combining that with the html image elements.我考虑过使用querySelectorAll('*')遍历所有元素并检查它们的style.backgroundstyle.backgroundImage属性的url ,然后将其与 html 图像元素结合。

Is that approach my only choice?那是我唯一的选择吗? Will that catch everything?那会抓住一切吗? I imagine there are edge cases with images loaded by JavaScript, new HTML5 image elements (picture, ...).我想有一些边缘情况,图像由 JavaScript 加载,新的 HTML5 图像元素(图片,...)。

I'm not yet sure how I want to handle data-uri images or SVG, but if an answer covered that, it'd probably be a good thing.我还不确定我想如何处理 data-uri 图像或 SVG,但如果答案涵盖了这一点,那可能是一件好事。

Made a new answer, this one will find all elements with a certian background, and can definitely be modified for all items that have a background or a couple different backgrounds.做了一个新的答案,这个答案会找到所有具有特定背景的元素,并且绝对可以针对具有背景或几个不同背景的所有项目进行修改。

Also you could modify for length of string, make sure it isn't an empty string and therefore has a background and then count that element.您也可以修改字符串的长度,确保它不是空字符串,因此具有背景,然后计算该元素。

* JavaScript Solution * * JavaScript 解决方案 *

I would say going though all elements is your only choice by what you have stated.我会说,尽管所有元素都是您所说的唯一选择。

 var count = 0; window.onload = function () { var elems = document.body.getElementsByTagName("*"); for(var i = 0; i < elems.length; i++) { var properties = (elems[i].currentStyle || window.getComputedStyle(elems[i], false)); background = properties.backgroundImage.slice(4, -1); if(background.indexOf("http://placehold.it/50x50") > -1) { count++; } } alert(count); };
 p { background: url('http://placehold.it/50x50'); }
 <div class="main"> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> </div>

Yes, I think you have to search through all elements and for each one obtain its image, depending on the type of element.是的,我认为您必须搜索所有元素并为每个元素获取其图像,具体取决于元素的类型。

Here's a functional code that will give you all images in a webpage inside IMG tags and also other common places (DIVs, Ps, etc).这是一个功能代码,它将为您提供 IMG 标签内网页中的所有图像以及其他常见位置(DIV、Ps 等)。 You can expand the search to other tags, or even to all tags.您可以将搜索扩展到其他标签,甚至所有标签。 It won't search in SVG and other " non-basic " forms of placing images:它不会在 SVG 和其他放置图像的“非基本”形式中搜索:

var imageSearch = 
{
    image_array: {},
    valid_image_nodes: ["DIV", "P", "SECTION", "SPAN"],

    scan_for_valid_images: function(node) 
    {
        if (node.nodeType === 1) 
        {
            if (node.nodeName === "IMG") {
                this.image_array[node.getAttribute("src")] = true;
            }
            else
            {
                if (this.valid_image_nodes.indexOf(node.nodeName) !== -1) {
                    div_style = node.currentStyle || window.getComputedStyle(node, false);
                    if (div_style.backgroundImage !== "none") {
                        url = div_style.backgroundImage;
                        this.image_array[url.slice(4, url.indexOf(')'))] = true;
                    }
                }
            }
        }
        var children = node.childNodes;
        for (var i = 0; i < children.length; i++) {
            this.scan_for_valid_images(children[i]);
        }
    },

    get_image_array: function()
    {
        return Object.keys(this.image_array)
    }
}

imageSearch.scan_for_valid_images(document);
imageSearch.get_image_array()

Try copy-pasting that into the console of this window to see it in action.尝试将其复制粘贴到此窗口的控制台中以查看其运行情况。

You can count with CSS using the counter-reset and counter-increment and count items with CSS.您可以使用 CSS 计数,使用counter-resetcounter-increment并使用 CSS 计数项目。

 body { counter-reset: img; } img { counter-increment: img; content:counter(img); content:""; } div.main:after { content: "Images Counted: " counter(img); }
 <div class="main"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> </div>

However to count all the items you want you could do:但是,要计算您想要的所有项目,您可以:

 body { counter-reset: count; } img { counter-increment: count; content:counter(count); content:""; } p:before { counter-increment: count; content:counter(count); content:""; } h1:before { counter-increment: count; content:counter(count); content:""; } div.main:after { content: "Items Counted: " counter(count); }
 <div class="main"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <img src="http://placehold.it/50x50"> <p> This paragraph is also counted </p> <h1> This header 1 is also counted </h1> </div>

You could also place this information in a hidden div and extract it later, if needed.如果需要,您还可以将此信息放在隐藏的div并稍后提取。

Here is something for reference: http://www.webdesignerdepot.com/2013/05/learn-to-count-with-css/这里有一些可供参考: http : //www.webdesignerdepot.com/2013/05/learn-to-count-with-css/

You can do the following at the bottom of the page:您可以在页面底部执行以下操作:

<script type="text/javascript">
    var imgCount = document.images.length;
    var svgCount = document.getElementsByTagName('svg').length;
    var finalCount = imgCount + svgCount;
</script>

with jquery you can use something like this for counter backgroundImage使用 jquery,你可以使用这样的东西作为计数器 backgroundImage

var ctBkImg = 0;
$("*").each(function(){
    if ($(this).css("background-image") != "none" ) ctBkImg++
}); 

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

相关问题 Selenium:如何从网站中提取所有图像(包括来自 javascript 和 css 的图像) - Selenium: how to extract all images from a website (including ones from javascript and css) 如何使用javascript / JQuery在所有dom图像上交换img src中的一个术语? - How can i swap one term in img src on all dom images using javascript / JQuery? 如何在JavaScript中检查一个数组是否包含另一个数组的所有元素,包括count? - How can I check it an array contains all elements from another array, including count, in JavaScript? 如何使用JavaScript获取页面上所有图像的href? - How can I get the href of all images on a page using JavaScript? 在页面中包含JavaScript和CSS(jQuery) - Including JavaScript and CSS in a page (jQuery) 如何替换所有空的<img src="">在 dom 上加载了 JavaScript 的页面上? - How to replace all empty <img src=""> on a page with JavaScript on dom loaded? 如何将CSS参数链接到javascript img? - How can I link CSS parameters to a javascript img? Javascript检测所有图像(包括异步) - Javascript Detect All Images (Including Asynchronous) 替换页面加载时的所有img src-Javascript - Replace all img src on page load - Javascript 如何更改页面中所有元素的CSS-JavaScript - How to change the CSS of all the elements in the page - JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM