zoukankan      html  css  js  c++  java
  • jquery判断元素是否出现在可视区

     

    在我们的日常开发中,经常会遇到当元素出现在可视区的时候需要去出发某一事件的情况。
    我最近在优化环球网首页的时候,将非可视区的代码全部放入到webComponent中。打算当这个元素出现在可视区的时候去加载对应的shadowRoot。

    那么,言归正传,对于我这个前端小白,还是好先搞定如何判断元素出现在可视区啊!

    jquery实现起来比较简单,先解释下几个东东

    offset().top和offsetTop;
    offsetTop:元素border外侧到offsetParent()的偏移量。(offsetParent():是元素的第一级拥有定位属性(absolute/relative/fixed)的父元素).
    offset().top:到document的绝对偏移量,这个当然就是我们需要的。offset().top当浏览器出现滚动条的时候,offset().top是不会变化的,当没有滚动条的时候,这个值是会变化的(可以理解的哈)。
    outHeight(): 元素的height+padding+border
    outHeight(true):元素的height+padding+border+margin
    $(window).height():浏览器可视窗口的高度
    $(window).scrollTop():document的顶部和浏览器顶部的距离


    所以我们就可以很简单的判断元素是不是出现在浏览器可视区了:
    代码如下(这里我故意加了个div,position为relative)


     

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
        <meta charset="utf-8">
        <title>js</title>
        <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $(window).scroll(function () {
                    var a = $("#eq").offset().top;
                    console.log(a);
                    console.log($(window).scrollTop());
                    console.log($(window).height());
                    if (a >= $(window).scrollTop() && a < ($(window).scrollTop() + $(window).height())) {
                        console.log("div在可视范围");
                    }
                });
            });
        </script>
    </head>
    <body>
    <div style="1px;height:2000px; -webkit-tap-highlight-color: transparent;">></div>
    <div style="position:relative">
        <div id="eq" style=" 100px; height:100px; ">1</div>
    </div>
    <div style="1px;height:2000px; -webkit-tap-highlight-color: transparent;">></div>
    </body>
    </html>
  • 相关阅读:
    Java WebService异构系统通信的原理及特点:SOAP与WSDL
    jenkins下拉框选择构建环境
    vue中的hash与history
    一行代码轻松搞定企微内嵌h5调用原生api不生效问题
    开源绘图工具plantUML入门教程(常用于画时序图等)
    什么是持续集成、持续交付、持续部署(CI/CD)?
    一篇文章了解CI/CD管道全流程
    开源免费的SSH工具推荐:electerm(推荐)、Finalshell
    Oracle数据库设置表空间自动扩展(解决因表空间不足引起的ORA01653: unable to extend table错误)
    测试工作中浏览器F12工具简单使用介绍
  • 原文地址:https://www.cnblogs.com/gluncle/p/9117736.html
Copyright © 2011-2022 走看看