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

纵然是瞬间 提交于 2020-01-06 14:04:12

问题


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. 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?


回答1:


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; to that particular class in 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 :)




回答2:


$(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.

$(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>



回答3:


Check what returns $(this), use console log for it.



来源:https://stackoverflow.com/questions/29793301/jquery-hide-only-visible-images-before-load-on-document-ready

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!