1.需求:
banner图在可视窗口内展示程度达到80%以上即触发一个事件(由于banner图是满屏宽,因此不需要考虑高度)
2.分析:
- 判断banner图何时不在可见范围内
- 当banner图的底部线条在可见区域下方超过20%即为不在可见范围
- 当banner图的顶部线条在可见区域上方超过20%即为不在可见范围
3.代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 100%;
height: 200px;
background: #1c65b9;
margin-bottom: 10px;
text-align: center;
line-height: 200px;
font-size: 40px;
}
.banner {
color: #ffe600;
background: #dd1ca3;
}
</style>
</head>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div class="banner">6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<script type="text/javascript">
var banner = document.querySelector(".banner");
document.addEventListener("scroll", function () {
var scope = (banner.offsetHeight * (100 - 80)) / 100; //广告栏可出线范围大小
var cH = document.documentElement.clientHeight; //当前页面可见区域高度
var tY = banner.getBoundingClientRect().top; //广告栏顶部到可见区域顶端的高度
var bY = banner.getBoundingClientRect().bottom; //广告栏底部到可见区域顶端的高度
// 需要考虑两种可能 当tY小于-scope则代表不在窗口展示 当bY大于cH+scope则代表不在窗口展示
if (tY < -scope || bY > cH + scope) {
console.log("不在可见范围内");
} else {
console.log("在可见范围内:", "触发事件");
}
});
</script>
</body>
</html>