从HTMLCollection创建数组后,为什么image的clientHeight为0?

时间:2019-07-19 00:00:42

标签: javascript html

因此,我正在执行GET请求以取消启动以将图像加载到页面上。我想获取已加载图像的clientHeight,以便可以在每个图像上操纵CSS网格跨度属性。我可以获取图像及其clientHeights,但是当我使用Array.from从HTMLCollection创建数组时,新数组中的项目的clientHeight为0,我不确定为什么。感谢您的帮助!

这是我完整的JS代码:


axios
    .get('https://api.unsplash.com/photos/random', {
        params: { count: 5 },
        headers: {
            Authorization: `Client-ID ${ID}`
        }
    })
    .then(response => {
        let html = '';

        response.data.forEach(image => {
            html += `

                    <img src=${image.urls.regular} alt=${
                image.alt_description
            } />

            `;
        });
        document.getElementById('posts').innerHTML = html;
        updateHTML();
    });


const updateHTML = () => {
    let postsHTML = document.getElementsByTagName('img');
    console.log(postsHTML);
    let postsArray = Array.from(postsHTML);
    console.log(postsArray);

    let html = '';

    postsArray.map(post => {
        console.log(post.clientHeight);
        const span = setSpans(post.clientHeight);

        html += `
                <img src=${post.src} alt=${
            post.alt
        } style="grid-row-end: span ${span}"/>
            `;
    });

    console.log(html);

    document.getElementById('posts').innerHTML = html;
};

const setSpans = height => {
    return Math.ceil(height / 10 + 1);
};

1 个答案:

答案 0 :(得分:0)

您的图像仍处于加载状态,无法获得正确的clientHeight。您需要处理图片的onload事件,然后查询clientHeight。