Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
81 views
in Technique[技术] by (71.8m points)

javascript - Getting dimensions of Element with image inside that loads late

I'm currently struggeling with getting the width of a element 'slides' by using offsetWidth.

var slide = $('.slides');

console.log(slide[0].offsetWidth);
console.log(slide[1].offsetWidth);

all the Elements in slides have a different width. However it returns the same value for all Elements and thats only true for the first Element.

The Elements have a width: min-content property.

.slides{
    width: min-content;
}

Inside the 'slides' Elements is a <img> Element and each has a individual aspect ratio but the same height.

.slides img{
    max-width: inherit;
    height: 35vw;
}
question from:https://stackoverflow.com/questions/65951131/getting-dimensions-of-element-with-image-inside-that-loads-late

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem Solved.

If you have the same issue, check if the content inside the child doesn't get loaded late. Like in my case the image inside gets loaded after it is in the viewport. That means it hasn't had a width until then.

I solved it that way:

this code snipped waits for the images to load in order to get the width

var counter = 0;
$(document).ready(function(){
    images_length = $('.gallery-image').length;
    //i needed to wait until all images have loaded so i picked the last image that fires the last event.
    $('.gallery-image').on("load", function() {
        if(counter == images_length -1){
            var slides = $('.gallery-slide', this);
            for (let i = 0; i < slides.length; i++) {
                 console.log(slides[i].offsetWidth);
            }
        }
        counter++;
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...