![](/img/trans.png)
[英]Limit the browser windows height can not less than 200 px using Jquery?
[英]First image in <body> greater than 200 px Using Jquery
對於社交媒體共享,我嘗試使用jQuery獲得大於200像素的第一個圖像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"/>
這是我發現的元標記的有效選擇器:
$('meta[property=og\\:image]').attr('content','new-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);
但是if ($(this).height() > $minHeight)
, if ($(this).height() > $minHeight)
上述腳本無法按需使用大於號
因此,當您執行$(“ body img”)時,jquery返回一個元素數組。
如果我理解正確,那么您需要的圖像應該是ACTUAL HEIGHT,但不是CSS提供的高度。 在這種情況下:
var ImagesGreaterThan200Height =jQuery.grep($("body img"), function( img, i ) {
if(img.naturalHeight > 200)
return img;
});
從上面的代碼中,您將獲得一個高度大於200px的圖像數組,對於第一個圖像,您只需要執行以下操作:
ImagesGreaterThan200Height[0] // This returns the first Image
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.