当元素处于可视区域时再加载,例如淘宝天猫上打开网页时不是所有图片都加载出来了,而是当滚动条滚动到那个区域时才加载出来图片。
方法:判断元素顶部到浏览器窗口顶部的距离是否小于可视区域高度,如果小于就显示。这里可以用一个方法: getBoundingClientRect(),该方法返回一个对象,该对象存储了元素四个边界到浏览器窗口上边和左边的距离。
getBoundingClientRect方法:
1.语法:这个方法没有参数。
rectObject = object.getBoundingClientRect();
2.返回值类型:TextRectangle对象,每个矩形具有四个整数性质( 上, 右 , 下,和左 )表示的坐标的矩形,以像素为单位。
rectObject.top:元素上边到视窗上边的距离;
rectObject.right:元素右边到视窗左边的距离;
rectObject.bottom:元素下边到视窗上边的距离;
rectObject.left:元素左边到视窗左边的距离;
示图:
3.兼容性:我用ie11的Document Mode模式测试,ie5以上都能支持。
PC端:
Mobile端:
4.width和height:ie9以上支持width/height属性。
兼容ie6~ie8的width/height的写法:
var rectWidth = rectObject.right - rectObject.left;
rectHeight = rectObject.bottom - rectObject.top;
复制代码
5.样例
<!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>
复制代码