Javascript 第一个图像在<;车身>;使用Jquery时大于200 px

Javascript 第一个图像在<;车身>;使用Jquery时大于200 px,javascript,jquery,Javascript,Jquery,对于社交媒体共享,我尝试使用jQuery获取第一个大于200px的图像URL。这是我不工作的代码: $("body img").each(function() { var $minHeight = 200; if ($(this).height() > $minHeight) { $(this).attr('src') } }); 在获得正确的图像后,我需要在下面的content=“default image.png”中更改默认图像URL: <meta prop

对于社交媒体共享,我尝试使用jQuery获取第一个大于200px的图像URL。这是我不工作的代码:

$("body img").each(function() {
  var $minHeight = 200;
  if ($(this).height() > $minHeight) {
    $(this).attr('src')
  }
});
在获得正确的图像后,我需要在下面的
content=“default image.png”
中更改默认图像URL:

<meta property="og:image" name="twitter:image" content="default-image.png"/>
我发现我的代码正在工作,但是

$("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);
$(“body img”)。每个(函数(){
var$minHeight=200;
如果($(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);
但是上面的脚本不能根据需要使用大于号的if($(this).height()>$minHeight)所以,当您使用$(“body img”)时,jquery返回一个元素数组

如果我理解正确,你需要的图像是实际高度,但不是CSS提供的高度。在这种情况下:

var ImagesGreaterThan200Height =jQuery.grep($("body img"), function( img, i ) {
    if(img.naturalHeight > 200)
         return img;
});
从上面的代码中,您将获得一组高度大于200px的图像,对于第一幅图像,您只需执行以下操作:

ImagesGreaterThan200Height[0] // This returns the first Image

希望这有帮助

语法错误:
)。(“
@Vohuman我应该使用什么?这取决于您试图实现的目标。
('meta[property=og\\\:image]”的角色是什么
?请注意,即使在获取元素高度之前,您也应该先听一下加载的
。@blackfire css中背景图像是如何定义的?@Vohuman我编辑了这个问题
ImagesGreaterThan200Height[0] // This returns the first Image