[英]Get the Height of an Image
這應該很容易,但事實並非如此。 我只需要圖像的高度:
<div id="map">
<img src="myimage.jpg">
</div>
$("#map img").height(); // returns 0
使用.clientHeight
(純 JavaScript):
https://jsfiddle.net/ryanpcmcquen/v6yz8t3u/
console.log(document.querySelector('img').clientHeight);
<img src="//makelin.us/100/100" />
在這里閱讀: https : //developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight
請注意,這將為您提供圖像在頁面上顯示的高度,它可能受 CSS 影響。
注意:要獲取圖像的實際高度,請使用.naturalHeight
。
很棒的文章: https : //davidwalsh.name/get-image-dimensions
要確保在圖像加載后運行,請執行以下操作:
window.addEventListener('load', function () {
console.log(document.querySelector('img').clientHeight);
});
問題是還沒有計算高度或寬度,用.on( "load", handler )監聽圖片的加載
$("#map img").on("load", function(){ var height = $(this).height(); $('#output').html('height=' + height); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script> <div id="map"> <img src="http://placehold.it/400x40"> </div> <div id="output"></div>
您可以參考以下示例來獲取圖像的高度-
<div id="map">
<img id="img_id" src="http://www.clickerzoneuk.co.uk/cz/wp-content/uploads/2010/10/PuppySmall.jpg" >
</div>
在js文件中寫入以下代碼
var height = document.getElementById("img_id").clientHeight;
alert(height);
使用以下鏈接檢查示例 -
這對我有用:
$(window).load(function () {
var artLists = [];
$("ul.articles").each(function (index) {
var imageHts = [];
$("li img", $(this)).each(function () {
imageHts.push($(this)[0].height);
})
artLists.push(imageHts);
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.