zoukankan      html  css  js  c++  java
  • JS 滚动条滚动到指定元素触发

    JS 版

    <!DOCTYPE html>
    <html>
    
    <head>
        <style type="text/css">
            #showIt {
                 200px;
                height: 200px;
                background-color: red;
                position: absolute;
                top: 1500px;
            }
        </style>
    </head>
    
    <body style="height:2000px;">
        <div id="showIt"></div>
    </body>
    <script type="text/javascript">
        document.onscroll = function() {
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            var cHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            var oDiv = document.getElementById('showIt');
            if (scrollTop > (oDiv.offsetTop - cHeight))
                alert('触发了')
        }
    </script>
    
    </html>

    JQ版 

    $(document).scroll(function() {
        sTop = $(this).scrollTop(); //获取滚动条的位置
        var sh = $(window).height();//视口高度
        var ft = $("footer").offset().top//指定元素距离文档顶部高度
        
        // 滚动条位置 大于 指定元素减去 视口高度时
        if (sTop > (ft - sh)) { //当底部出现在视口时 触发
            //dododo
        }
    }
  • 相关阅读:
    JS的运行机制
    Vue路由
    javascript的逼格
    Vue开发中遇到的问题及解决方案
    模块模式
    2019年终总结
    http知识总结
    小议函数的节流和防抖
    nodejs初探一二
    Object是个什么鬼
  • 原文地址:https://www.cnblogs.com/xzma/p/7698668.html
Copyright © 2011-2022 走看看