[英]how to get the height and width of image in javascript?
我有一個代碼,我試圖在其中獲取所有圖像標簽的高度和寬度。
var img = $('.data').find('img');
$.each($(img), function() {
console.log('first', this.height, $(this).height, $(this).height());
console.log('second', $(this).clientHeight, $(this).naturalHeight);
console.log('third', $(this)[0].height, $(this)[0].clientHeight, $(this)[0].naturalHeight);
console.log($(this).attr('height'), $(this).prop('height')); });
即使我在循環中嘗試了
img
。嘗試與寬度相同,結果將是 0 或未定義。 對
width
嘗試了同樣的事情。
你能告訴我哪里做錯了嗎
你正在傳遞$(img)
這應該只是你里面的img
$.each
。如果你的圖像有name
屬性,你也可以打印console.log('first',..
而不是這個。
這是演示代碼:
var img = $('.data').find('img'); $.each(img, function() { console.log($(this).attr("name") + "-> Height: " + $(this)[0].height + " Width:" + $(this)[0].width); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="data"> <img name="image1" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain@2x.jpg" style="height:70px;width:70px"> <img name="image2" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain@2x.jpg" style="height:40px;width:40px"> <img name="image3" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain@2x.jpg" style="height:50px;width:50px"> </div>
我沒有得到圖像的高度和寬度,因為圖像load
事件在加載過程中發生得很晚
最后我找到了答案
var img = $('.data').find('img');
$.each(img, function() {
$(this).bind('load', function() {
console.log($(this).height);
}
});
它適用於img
和$(img)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.