zoukankan      html  css  js  c++  java
  • 如何判断一个元素是不是可见

    function isElementInViewport (el) {
    
        //special bonus for those using jQuery
        if (typeof jQuery === "function" && el instanceof jQuery) {
            el = el[0];
        }
    
        var rect = el.getBoundingClientRect();
    
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
        );
    }

    --

    https://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433

    function onVisibilityChange(el, callback) {
        var old_visible;
        return function () {
            var visible = isElementInViewport(el);
            if (visible != old_visible) {
                old_visible = visible;
                if (typeof callback == 'function') {
                    callback();
                }
            }
        }
    }
    
    var handler = onVisibilityChange(el, function() {
        /* your code go here */
    });
    
    
    //jQuery
    $(window).on('DOMContentLoaded load resize scroll', handler); 
    
    /* //non-jQuery
    if (window.addEventListener) {
        addEventListener('DOMContentLoaded', handler, false); 
        addEventListener('load', handler, false); 
        addEventListener('scroll', handler, false); 
        addEventListener('resize', handler, false); 
    } else if (window.attachEvent)  {
        attachEvent('onDOMContentLoaded', handler); // IE9+ :(
        attachEvent('onload', handler);
        attachEvent('onscroll', handler);
        attachEvent('onresize', handler);
    }


    ---
  • 相关阅读:
    Sum Root to Leaf Numbers深度优先计算路径和
    Path Sum II深度优先找路径
    动态和静态链接库
    C/C++变量
    搜索
    基本格式
    随机数生成函数
    珍惜生命,我用Python 。今天开始学习Python
    在windows里hexo 博客创建步骤
    作为一个程序员,什么是脚本。必须要理解
  • 原文地址:https://www.cnblogs.com/qinqiu/p/9340499.html
Copyright © 2011-2022 走看看