Home > Article > Web Front-end > js visual area loading: getBoundingClientRect method
Load when the element is in the visible area. For example, when the web page is opened on Taobao and Tmall, not all images are loaded, but when the scroll bar scrolls to that area, the images are loaded.
Method: Determine whether the distance from the top of the element to the top of the browser window is less than the height of the visual area. If it is less, display it. You can use a method here: getBoundingClientRect(), which returns an object that stores the distance from the four edges of the element to the top and left side of the browser window.
getBoundingClientRect method:
##Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>可视区域加载</title> <style> #showp { width: 500px; height: 350px; background-color: aqua; margin: 1000px auto 0 auto; } .showp { animation: loading 2s linear; } @keyframes loading { from { opacity: 0; transform: translate(-100%, 0); } to { opacity: 1; transform: translate(0, 0); } } </style> </head> <body> <p id="showp"></p> <script type="text/javascript"> window.onscroll = function() { var show = document.getElementById("showp"); // 获取浏览器窗口可视化高度 var clientH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; // 获取showp元素顶部到浏览器窗口顶部的距离 var showTop = show.getBoundingClientRect().top; // 如果距离小于可视化窗口高度,就给showp元素添加动画效果 if (showTop <= clientH) { show.classList.add("showp"); } }; </script> </body> </html>
Run result :do not know why. . . The resulting animation cannot be posted. . . . Just describe it orally: the animation will not load at the beginning, and the animation will not start loading until the scroll bar scrolls to the point where the element can be displayed. This principle can be used to load images, which is to assign the src value to the image when it reaches the visible area. Related recommendations:
View the larger image and click on the larger image to hide
The above is the detailed content of js visual area loading: getBoundingClientRect method. For more information, please follow other related articles on the PHP Chinese website!