Py学习  »  Jquery

当内容位于可见视区时启动jquery动画

Cray • 5 年前 • 2779 次点击  

我正在通过ajax加载元素。其中一些只有向下滚动页面时才可见。
有没有办法让我知道一个元素现在是否在页面的可见部分?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44325
 
2779 次点击  
文章 [ 30 ]  |  最新文章 5 年前
Domysee
Reply   •   1 楼
Domysee    8 年前

这里的大多数答案都没有考虑到元素也可以隐藏,因为它是从div的视图中滚动出来的,而不仅仅是整个页面。

为了覆盖这种可能性,基本上必须检查元素是否位于其父元素的边界内。

这个解决方案确实做到了:

function(element, percentX, percentY){
    var tolerance = 0.01;   //needed because the rects returned by getBoundingClientRect provide the position up to 10 decimals
    if(percentX == null){
        percentX = 100;
    }
    if(percentY == null){
        percentY = 100;
    }

    var elementRect = element.getBoundingClientRect();
    var parentRects = [];

    while(element.parentElement != null){
        parentRects.push(element.parentElement.getBoundingClientRect());
        element = element.parentElement;
    }

    var visibleInAllParents = parentRects.every(function(parentRect){
        var visiblePixelX = Math.min(elementRect.right, parentRect.right) - Math.max(elementRect.left, parentRect.left);
        var visiblePixelY = Math.min(elementRect.bottom, parentRect.bottom) - Math.max(elementRect.top, parentRect.top);
        var visiblePercentageX = visiblePixelX / elementRect.width * 100;
        var visiblePercentageY = visiblePixelY / elementRect.height * 100;
        return visiblePercentageX + tolerance > percentX && visiblePercentageY + tolerance > percentY;
    });
    return visibleInAllParents;
};

它还允许您指定它在每个方向上的可见百分比。
它不包括由于其他因素而隐藏的可能性,比如 display: hidden .

这应该适用于所有主流浏览器,因为它只使用 getBoundingClientRect . 我在chrome和internet explorer 11中亲自测试过。

Snigdha Batra
Reply   •   2 楼
Snigdha Batra    12 年前

tweeked scott dowding的酷函数满足我的需求- 这用于查找元素是否刚刚滚动到屏幕上,即它的上边缘。

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
}
Sampson
Reply   •   3 楼
Sampson    16 年前

WebResourcesDepot 写的 a script to load while scrolling 使用的 jQuery 不久前。你可以查看他们的 Live Demo Here . 他们最大的功能就是:

$(window).scroll(function(){
  if  ($(window).scrollTop() == $(document).height() - $(window).height()){
    lastAddedLiveFunc();
  }
});

function lastAddedLiveFunc() { 
  $('div#lastPostsLoader').html('<img src="images/bigLoader.gif">');
  $.post("default.asp?action=getLastPosts&lastPostID="+$(".wrdLatest:last").attr("id"),
    function(data){
        if (data != "") {
          $(".wrdLatest:last").after(data);         
        }
      $('div#lastPostsLoader').empty();
    });
};
vsync
Reply   •   4 楼
vsync    6 年前

使用(“new”) IntersectionObserver 美国石油学会

确定元素是否在视口中可见是非常容易和有效的。通过使用 观察者 ,它不需要附加 scroll 事件并手动检查事件回调。

// this is the target which is observed
var target = document.querySelector('div');

// configure the intersection observer instance
var intersectionObserverOptions = {
  root: null,
  rootMargin: '150px',
  threshold: 1.0
}
    
var observer = new IntersectionObserver(onIntersection, intersectionObserverOptions);

// provice the observer with a target
observer.observe(target);

function onIntersection(entries){
  entries.forEach(entry => {
    console.clear();
    console.log(entry.intersectionRatio)
    target.classList.toggle('visible', entry.intersectionRatio > 0);
    
    // Are we in viewport?
    if (entry.intersectionRatio > 0) {
      // Stop watching 
      // observer.unobserve(entry.target);
    }
  });
}
.box{ width:100px; height:100px; background:red; margin:1000px; }
.box.visible{ background:green; }
Scroll both Vertically & Horizontally...
<div class='box'></div>

View browsers support table (IE/Safari不支持)

sectus webicy
Reply   •   5 楼
sectus webicy    9 年前

怎么样

function isInView(elem){
   return $(elem).offset().top - $(window).scrollTop() < $(elem).height() ;
}

在那之后,一旦元素像这样出现在视图中,你就可以触发你想要的任何东西

$(window).scroll(function(){
   if (isInView($('.classOfDivToCheck')))
      //fire whatever you what 
      dothis();
})

对我来说很好

Fedir RYKHTIK
Reply   •   6 楼
Fedir RYKHTIK    13 年前

jquery航路点插件在这里非常好。

$('.entry').waypoint(function() {
   alert('You have scrolled to an entry.');
});

有一些关于 site of the plugin .

Ally
Reply   •   7 楼
Ally    6 年前

这是我的纯javascript解决方案,如果它也隐藏在一个可滚动的容器中,那么它也可以工作。

Demo here (也尝试调整窗口大小)

var visibleY = function(el){
  var rect = el.getBoundingClientRect(), top = rect.top, height = rect.height, 
    el = el.parentNode
  // Check if bottom of the element is off the page
  if (rect.bottom < 0) return false
  // Check its within the document viewport
  if (top > document.documentElement.clientHeight) return false
  do {
    rect = el.getBoundingClientRect()
    if (top <= rect.bottom === false) return false
    // Check if the element is out of view due to a container scrolling
    if ((top + height) <= rect.top) return false
    el = el.parentNode
  } while (el != document.body)
  return true
};

编辑2016-03-26:我已经更新了解决方案,以说明滚动过元素,因此它隐藏在可滚动容器顶部上方。 编辑2018-10-08:在屏幕上方滚动出视图时更新为处理。

Aoi Karasu
Reply   •   8 楼
Aoi Karasu    12 年前

到目前为止,我发现最好的方法是 jQuery appear plugin . 很有魅力。

模拟一个自定义的“出现”事件,当元素滚动到视图中或以其他方式对用户可见时触发。

$('#foo').appear(function() {
  $(this).text('Hello world');
});

此插件可用于防止对隐藏或不在可视区域内的内容的不必要请求。

jcubic
Reply   •   9 楼
jcubic    7 年前

This answer 香草:

function isScrolledIntoView(el) {
    var rect = el.getBoundingClientRect();
    var elemTop = rect.top;
    var elemBottom = rect.bottom;

    // Only completely visible elements return true:
    var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
    // Partially visible elements return true:
    //isVisible = elemTop < window.innerHeight && elemBottom >= 0;
    return isVisible;
}
Andrea Casaccia Scott Dowding
Reply   •   10 楼
Andrea Casaccia Scott Dowding    8 年前

这应该可以做到:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

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

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

简单效用函数 这将允许您调用一个实用程序函数,该函数接受您要查找的元素,并且如果您希望元素完全在视图中或部分在视图中。

function Utils() {

}

Utils.prototype = {
    constructor: Utils,
    isElementInView: function (element, fullyInView) {
        var pageTop = $(window).scrollTop();
        var pageBottom = pageTop + $(window).height();
        var elementTop = $(element).offset().top;
        var elementBottom = elementTop + $(element).height();

        if (fullyInView === true) {
            return ((pageTop < elementTop) && (pageBottom > elementBottom));
        } else {
            return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
        }
    }
};

var Utils = new Utils();

使用

var isElementInView = Utils.isElementInView($('#flyout-left-container'), false);

if (isElementInView) {
    console.log('in view');
} else {
    console.log('out of view');
}