我通过AJAX加载元素。其中一些只有当你向下滚动页面时才能看到。有什么方法可以知道元素现在是否在页面的可见部分?


当前回答

我添加了我的代码修改。不幸的是,我可以看到每个人都在他们的版本,每个人都忽略了debance功能的使用。哪个答案是让你的事件不触发,例如,在滚动时每秒200次。

$(window).scroll(function(){
        if (isInView($('.class'))){
            debounce(
                someFunction(), 5
            )
        }
    });
    function isInView(elem){
        if(document.documentElement.clientWidth > 991){
            return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
        }else {
            doSometing;
        }
    }

其他回答

我添加了我的代码修改。不幸的是,我可以看到每个人都在他们的版本,每个人都忽略了debance功能的使用。哪个答案是让你的事件不触发,例如,在滚动时每秒200次。

$(window).scroll(function(){
        if (isInView($('.class'))){
            debounce(
                someFunction(), 5
            )
        }
    });
    function isInView(elem){
        if(document.documentElement.clientWidth > 991){
            return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
        }else {
            doSometing;
        }
    }

我改编了这个简短的jQuery函数扩展,你可以自由使用(MIT许可)。

/**
 * returns true if an element is visible, with decent performance
 * @param [scope] scope of the render-window instance; default: window
 * @returns {boolean}
 */
jQuery.fn.isOnScreen = function(scope){
    var element = this;
    if(!element){
        return;
    }
    var target = $(element);
    if(target.is(':visible') == false){
        return false;
    }
    scope = $(scope || window);
    var top = scope.scrollTop();
    var bot = top + scope.height();
    var elTop = target.offset().top;
    var elBot = elTop + target.height();

    return ((elBot <= bot) && (elTop >= top));
};

我需要检查可滚动DIV容器内元素的可见性

    //p = DIV container scrollable
    //e = element
    function visible_in_container(p, e) {
        var z = p.getBoundingClientRect();
        var r = e.getBoundingClientRect();

        // Check style visiblilty and off-limits
        return e.style.opacity > 0 && e.style.display !== 'none' &&
               e.style.visibility !== 'hidden' &&
               !(r.top > z.bottom || r.bottom < z.top ||
                 r.left > z.right || r.right < z.left);
    }

简单的检查元素(el)是否在可滚动的div (holder)中可见

function isElementVisible (el, holder) {
  holder = holder || document.body
  const { top, bottom, height } = el.getBoundingClientRect()
  const holderRect = holder.getBoundingClientRect()

  return top <= holderRect.top
    ? holderRect.top - top <= height
    : bottom - holderRect.bottom <= height
}

使用jQuery:

var el = $('tr:last').get(0);
var holder = $('table').get(0);
var isVisible = isElementVisible(el, holder);

如果你想在另一个div中滚动项目,

function isScrolledIntoView (elem, divID) 

{

    var docViewTop = $('#' + divID).scrollTop();


    var docViewBottom = docViewTop + $('#' + divID).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); 
}