简体   繁体   中英

First image in <body> greater than 200 px Using Jquery

For social media sharing I am trying to get the first image URL which is greater than 200px using jQuery. This is my code which is not working:

$("body img").each(function() {
  var $minHeight = 200;
  if ($(this).height() > $minHeight) {
    $(this).attr('src')
  }
});

After getting the right image I need to change the default image URL in content="default-image.png" below:

<meta property="og:image" name="twitter:image" content="default-image.png"/>

This is a working selector for meta tag I found:

$('meta[property=og\\:image]').attr('content','new-image.png');

I Found My Code Is Working But...

$("body img").each(function() {
  var $minHeight = 200;
  if ($(this).height() < $minHeight) {
  $x = $(this).attr('src')
  }
});

$('meta[property=og\\:image]').attr('content',$x);

$(".share a[href*='pinterest']").prop("href","https://pinterest.com/pin/create/button/?url=http://mywebsite.com/mypage&media="+$x);

But above script is not working with greater than sign as needed if ($(this).height() > $minHeight)

So, when you do $("body img") jquery returns an array of elements.

If I am understanding it correct, you need the image which is of ACTUAL HEIGHT but not the CSS provided height. In this case:

var ImagesGreaterThan200Height =jQuery.grep($("body img"), function( img, i ) {
    if(img.naturalHeight > 200)
         return img;
});

From the above code, you will get an array of Images which are greater than 200px in height and for the first image you just need to do:

ImagesGreaterThan200Height[0] // This returns the first Image

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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