簡體   English   中英

使用JavaScript Fetch Api從HTML文件中的圖像獲取高度

[英]Get the Height from The Image that get from A Html File by JavaScript Fetch Api

這些是我的代碼:

a.html

<div class="pic-box">
    <img src="a.jpg" alt="" />
</div>

index.html

<div class="get-box"></div>

index.js

const pageUrl = './pages/a.html',

fetch(url).then(function(response){
    if (response.ok) {
        return response.text();
    }
}).then((data) => {
    $('.get-box').html(data);
    const imageHeight = $('.get-box img').height();
    console.log(imageHeight);
});

我想獲取圖像的高度,但是顯示為0。如何獲得真實高度?

您應將a.html源代碼附加到<div class="get-box"></div>元素或替換為:

a.html

<div class="pic-box">
    <img src="a.jpg" alt="..." onload="imageLoaded(this)" />
</div>

如果您使用jQuery:

function imageLoaded(element){
    const imageHeight = $(element).height();
    console.log(imageHeight);
}

const url = './pages/a.html';

$.ajax({ url: url })
  .done(function(html) {
    // Append
    $(".get-box").append(html);

    // or Replace
    // $(".get-box").replaceWith(html);           
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM