jQuery get all images within an element larger than a specific size

 ̄綄美尐妖づ 提交于 2020-01-12 20:55:33

问题


So I have an image placeholder and I want to load the first image from the HTML within a DIV element that is larger than 70px width or height. Then provide a next and previous link to load the next image that is larger than 70px.

I know jQuery has a next & prev selector but I'm not sure how I would tie this in with next and previous links or specify an image size.


回答1:


To get all images larger that some size you can use something like this:

var allImages = $('img', yourDivElement)

var largeImages = allImages.filter(function(){
  return ($(this).width() > 70) || ($(this).height() > 70)
})

To get the next/prev is not harder:

var nextElement = $(imgElement).nextAll().filter(function(){
  return ($(this).width() > 70) || ($(this).height() > 70)
}).eq(0);

Previous sample can be overkill if you have a lot of images, so you may want to loop over 'em instead in this way:

var nextElement, nextSilblings = $(imgElement).nextAll();

for (var i=0;i<nextSilblings.length;i++){
  if (($(nextSilblings[i]).width() > 70) || ($(nextSilblings[i]).height() > 70)){
    nextElement = nextSilblings[i];
    break;
  }
}



回答2:


Do this in two steps:

1) tag the images that fit the criteria

$('#targetDiv img').each(function() {
      if($(this).height()>70) {
         $(this).addClass('biggie')
      }
})

2) Hook up navigation

var myPos = 0;

    $('#btnNext').click(function() {
        //copy this image to the placeholder 
        $('#placeholder').attr('src', $('#targetDiv .biggie').eq(myPos).attr('src'));
         myPos++;
         if(myPos>$('#targetDiv .biggie').length) {
            myPos = 0;
         }
    })

...do the save for the previous button, except decrement and change zero logic.



来源:https://stackoverflow.com/questions/8933183/jquery-get-all-images-within-an-element-larger-than-a-specific-size

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