判断滚动条到底部,图片懒加载

实现代码,懒加载图片

Vue逻辑也是一样的

1.关于scrollHeight ,scrollTop ,clientHeight 的图例

scrollHeight 其实就是总的高度,clientHeight就是当前窗口即当前可视区域的高度,scorlltop就是当前窗口距离顶部的高度。
在这里插入图片描述

2.使用document.documentElement.xxx|| document.body.xxx兼容的原因;

页面存在DTD,使用document.documentEelement.scrollTop获取滚动条距离;
页面不存在DTD,使用document.documentElement.scrollTop 或 document.body.scrollTop都可以获取到滚动条距离;

3.DTD概念

html每一个不同版本的规范都有不同的DTD文档声明。

是HTML5 的DTD文档声明,该文档声明是向下兼容的。

所以页面
DTD文档声明的注意点:
1、任何一个标准的HTML网页,第一行一定是DTD文档声明,也就是说DTD文档声明必须写在HTML的第一行
2、DTD文档声明不区分大小写,下面两种书写都是可以的

<!DOCTYPE html>
or
<!doctype html>

3、DTD文档声明不是一个标签;

4、DTD文档声明的作用是用于告诉浏览器我们的网页是用哪一个版本的标准编写的,以便方便浏览器解析和渲染,但是浏览器并不是完全依赖这个DTD文档声明,浏览器有一套属于自己的机制;

也就是说,DTD文档声明不写网页也能正常运行,但是由于W3C规定第一行必须协商DTD文档声明,所以必须遵守规定,无论如何,我们都应该在第一行协商DTD文档声明

4.代码案例

<style>
    .wrap {
        width: auto;
        height: 3000px;
    }

    .scroll {
        width: 200px;
        height: 200px;
        position: fixed;
        background-color: antiquewhite;
    }
</style>
<div class="wrap">
    <div class="scroll">

    </div>
</div>
<script>

    //节流throttle代码:
    function throttle(fun, delay) {
        let canRun = true; // 通过闭包保存一个标记
        return function () {
            if (!canRun) return;
            canRun = false;
            // 将外部传入的函数的执行放在setTimeout中
            setTimeout(() => {
                // 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
                // 当定时器没有执行的时候标记永远是false,在开头被return掉
                fun(...arguments);
                canRun = true;
            }, delay);
        };
    }
    const myWrap = document.querySelector(".wrap");
    let windowHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
    window.addEventListener('scroll', throttle(function () {
        // 变量 scrollHeight 是滚动条的总高度
        let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight

        // 变量 windowHeight 是可视区的高度
        let windowHeight = document.documentElement.clientHeight || document.body.clientHeight

        // 变量scrollTop为当前页面的滚动条纵坐标位置
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        // 滚动条到底部得距离 = 滚动条的总高度 - 可视区的高度 - 当前页面的滚动条纵坐标位置
        var scrollBottom = scrollHeight - windowHeight - scrollTop;
        console.log(scrollHeight,windowHeight,scrollTop);
        if (scrollBottom <= 0) {
            alert("进行图片请求")
        }

    }, 500))
</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

竹林海灵

谢谢义父

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值