![](/img/trans.png)
[英]Why can't I get the naturalHeight/naturalWidth of an image in javascript/JQuery?
[英]Random fails trying to get the naturalHeight and naturalWidth of an image
我有一些簡單的代碼可以檢查圖像的寬度和高度,如果它不是>= 120x90,它會得到visibility: hidden
放在它上面。
$(".video-thumbnail").each(function() {
var width = $(this).prop("naturalWidth");
var height = $(this).prop("naturalHeight");
if (width <= 120 && height <= 90) {
$(this).css("visibility", "hidden");
}
});
問題是這在某些頁面重新加載時隨機失敗(請參閱下面的編輯)。
我認為這可能是緩存或瀏覽器加載延遲問題。
編輯
確認要重現的事件序列:
有什么建議可以更可靠地運行嗎? 也許強制瀏覽器下載圖像文件? 不知道那會是什么樣子。
更可靠的解決方案是使用返回 promise 的HTMLImageElement.decode() ,一旦全分辨率圖像可供使用,該函數就會被解析,示例如下:
$(".video-thumbnail").each(function () { this.decode().then(() => { var width = $(this).prop("naturalWidth"); var height = $(this).prop("naturalHeight"); if (width <= 120 && height <= 90) { $(this).css("visibility", "hidden"); } }).catch((encodingError) => { // Do something with the error. }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img src="https://picsum.photos/121/91" class="video-thumbnail"> <img src="https://picsum.photos/121/91" class="video-thumbnail"> <img src="https://picsum.photos/119/89" class="video-thumbnail"> <img src="https://picsum.photos/121/91" class="video-thumbnail">
發布另一種方法,該方法與標記為正確的方法一樣有效,以供我將來參考:
$(window).on("load", function() {
$(".video-thumbnail").each(function() {
var width = $(this).prop("naturalWidth");
var height = $(this).prop("naturalHeight");
if (width <= 120 && height <= 90) {
$(this).css("visibility", "hidden");
}
});
});
調用$(window).on("load"...
first 是唯一的變化。有時圖像沒有用我的原始代碼加載。
資料來源:
好奇這與答案中標記為正確的代碼之間是否存在任何性能差異。 行為似乎是相同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.