从图像中获取高度,从JavaScript Fetch API的HTML File获取高度



这些是我的代码:

答.html

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

索引.html

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

索引.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>元素或替换:

答.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);           
  });

最新更新