简体   繁体   English

Javascript 加载事件监听器

[英]Javascript load Eventlistener

I just wanted to ask how do you ensure that element details (eg position in viewport, getBoundingClientRect) are correct when loading your page for the first time.我只是想问一下,在第一次加载页面时,如何确保元素详细信息(例如视口中的 position、getBoundingClientRect)是正确的。 Currently I have a problem with a normal div-element.目前我对普通的 div 元素有疑问。 It is displayed right after an image which i get with a fetch statement.它显示在我通过获取语句获得的图像之后。 I used the load-event on window and after the Page is loaded I get the information of the position of the div-element.我在 window 上使用了加载事件,在加载页面后,我得到了 div 元素的 position 的信息。 Unfortunately the load-fires before the Image is loaded and that means the position details are wrong.不幸的是,加载图像在加载之前触发,这意味着 position 详细信息是错误的。 How and when do you use the load Event?您如何以及何时使用加载事件? And what Else can i do to ensure i receive the right position details.我还能做些什么来确保我收到正确的 position 详细信息。

Html <div class="wrapperImg"></div> <div class="position"></div> Html <div class="wrapperImg"></div> <div class="position"></div>

Js window.addEventListener("load",()=>{console.log(document.querySelector(".position").getBoundingClientRect());} Js window.addEventListener("load",()=>{console.log(document.querySelector(".position").getBoundingClientRect());}

Many thanks Regards Kat非常感谢 问候 Kat

You'd need to call the getBoundingClientRect() after the image has loaded, which means when your fetch call has resolved (as it is executed asynchronously).您需要在图像加载后调用getBoundingClientRect() ,这意味着您的获取调用已解决(因为它是异步执行的)。

To keep in mind: The load event does not include asnyc fetched resources (as those are handled dynamically).请记住:加载事件不包括 asnyc 获取的资源(因为这些资源是动态处理的)。 For more info on the load event see the documentation .有关加载事件的更多信息, 请参阅文档

'load' event listener can also be applied on images like this: 'load'事件侦听器也可以像这样应用于图像:

 var img = new Image(); img.src = "img.jpg"; img.onload = function () { alert("image is loaded"); }

Also you can get getBoundingClientRect() properties after the fetch:您还可以在获取后获取getBoundingClientRect()属性:

 fetch('image.png').then(i => { //get size })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM