简体   繁体   English

jQuery-仅在准备好文档时隐藏可见图像(加载前)

[英]jQuery - hide only visible images (before load) on document ready

I'm developing a Chrome extension, and require a functionality such that I want to get all visible images as soon as possible (before they load), hide them and set some attribute. 我正在开发Chrome扩展程序,并且需要某种功能,以便我希望尽快(在加载之前)获取所有可见图像,隐藏它们并设置一些属性。 I've been trying this: 我一直在尝试:

$(document).ready(function () {
    $('img:visible').each(function() {
        $(this).css('visibility', 'hidden');
        $(this).attr('data-internalid', guid());
    });
});

But while debugging, I noticed that it's not even iterating through the loop. 但是在调试时,我注意到它甚至没有遍历循环。 What I'm missing here? 我在这里想念的是什么?

So, as I mentioned in my comments 所以,正如我在评论中提到的

Elements are considered visible if they consume space in the document. 如果元素占用了文档中的空间,则认为它们是可见的。 Visible elements have a width or height that is greater than zero. 可见元素的宽度或高度大于零。

So, one of your options would be to use 因此,您的选择之一就是使用

$(window).on('load', function() { ... });

You may also try an alternative, such as the following. 您也可以尝试以下方法。

  1. Have a class for all the images you'd later like to set attributes to. 为您以后要设置属性的所有图像提供一个类。
  2. Set display:none; 设置display:none; to that particular class in CSS. 到CSS中的特定类。
  3. On load (look at the first option), set your attributes and then display those images, either by removing the class (recommended) or setting inline styles (not pretty). 加载时(查看第一个选项),设置属性,然后显示这些图像,方法是删除类(推荐)或设置内联样式(不太漂亮)。

Hope that was clear :) 希望很清楚:)

$(document).ready(function (index) {
    $('img:visible').each(function() {
        $(this).css('visibility', 'hidden');
        $(this).attr('data-internalid', "test"); /*instead of guid().I think that function have some problem.Make sure it is defined or loaded properly*/
    });
});

The problem is with your guid() function.This code works fine on firefox and chrome.Please check the function.If the problem is not solved, then update your jquery if it is offline else please provide guid() function. 问题出在您的guid()函数上。此代码在Firefox和chrome上正常工作,请检查该函数。如果问题仍未解决,请更新您的jquery(如果它离线),否则请提供guid()函数。

 $(function(){ //$("#btn").click(function(){ $('img:visible').each(function() { $(this).css('visibility', 'hidden'); $(this).attr('data-internalid', "test"); }); // }); }); 
 img{ width:100px; height:100px; margin:10px } span{ display:block; cursor:pointer; } 
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <img src="http://www.clker.com/cliparts/w/o/d/I/G/A/smily-hi.png"> <img src="http://www.clker.com/cliparts/w/o/d/I/G/A/smily-hi.png"> <img src="http://www.clker.com/cliparts/w/o/d/I/G/A/smily-hi.png"> <span id="btn">Click me</span> 

检查返回$(this) ,并使用控制台日志。

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

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