检测可滚动div中的元素何时不在视图中

时间:2013-04-30 20:00:01

标签: javascript jquery html tracking viewport

我需要找到解决以下问题的好方法。我看到很多人都在询问是否有一个元素在页面或浏览器窗口的视图Port的内部或外部。我需要能够复制这个动作,但是在滚动的DIV中,有溢出:滚动例如。有没有人知道这个具体行动的好例子?

提前致谢。

8 个答案:

答案 0 :(得分:25)

之前我遇到过同样的问题,我最终得到了以下函数。第一个参数是元素检查,第二个是检查元素是否部分in-view.it仅用于垂直检查,你可以扩展它以检查水平滚动。

function checkInView(elem,partial)
{
    var container = $(".scrollable");
    var contHeight = container.height();
    var contTop = container.scrollTop();
    var contBottom = contTop + contHeight ;

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

    var isTotal = (elemTop >= 0 && elemBottom <=contHeight);
    var isPart = ((elemTop < 0 && elemBottom > 0 ) || (elemTop > 0 && elemTop <= container.height())) && partial ;

    return  isTotal  || isPart ;
}

jsFiddle上查看。

答案 1 :(得分:15)

这里是接受答案的纯javascript版本,不依赖于jQuery,并且对部分视图检测提供了一些修复,并支持顶视图之外的视图。

function checkInView(container, element, partial) {

    //Get container properties
    let cTop = container.scrollTop;
    let cBottom = cTop + container.clientHeight;

    //Get element properties
    let eTop = element.offsetTop;
    let eBottom = eTop + element.clientHeight;

    //Check if in view    
    let isTotal = (eTop >= cTop && eBottom <= cBottom);
    let isPartial = partial && (
      (eTop < cTop && eBottom > cTop) ||
      (eBottom > cBottom && eTop < cBottom)
    );

    //Return outcome
    return  (isTotal  || isPartial);
}

作为奖励,此功能可确保元素在视图中(如果不是(部分或全部)):

function ensureInView(container, element) {

    //Determine container top and bottom
    let cTop = container.scrollTop;
    let cBottom = cTop + container.clientHeight;

    //Determine element top and bottom
    let eTop = element.offsetTop;
    let eBottom = eTop + element.clientHeight;

    //Check if out of view
    if (eTop < cTop) {
      container.scrollTop -= (cTop - eTop);
    }
    else if (eBottom > cBottom) {
      container.scrollTop += (eBottom - cBottom);
    }
}

答案 2 :(得分:2)

这是一个纯粹的JavaScript解决方案。

function elementIsVisible(element, container, partial) {
    var contHeight = container.offsetHeight,
    elemTop = offset(element).top - offset(container).top,
    elemBottom = elemTop + element.offsetHeight;
    return (elemTop >= 0 && elemBottom <= contHeight) || 
    (partial && ((elemTop < 0 && elemBottom > 0 ) || (elemTop > 0 && elemTop <= contHeight)))
}

// checks window
function isWindow( obj ) {
    return obj != null && obj === obj.window;
}

// returns corresponding window
function getWindow( elem ) {
    return isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}

// taken from jquery
// @returns {{top: number, left: number}} 
function offset( elem ) {

    var docElem, win,
        box = { top: 0, left: 0 },
        doc = elem && elem.ownerDocument;

    docElem = doc.documentElement;

    if ( typeof elem.getBoundingClientRect !== typeof undefined ) {
        box = elem.getBoundingClientRect();
    }
    win = getWindow( doc );
    return {
        top: box.top + win.pageYOffset - docElem.clientTop,
        left: box.left + win.pageXOffset - docElem.clientLeft
    };
};

答案 3 :(得分:2)

基于最佳答案。而不仅仅是告诉你元素是否部分可见。我添加了一点额外的,所以你可以传入一个百分比(0-100),告诉你元素是否超过x%可见。

function (container, element, partial) {
    var cTop = container.scrollTop;
    var cBottom = cTop + container.clientHeight;
    var eTop = element.offsetTop;
    var eBottom = eTop + element.clientHeight;
    var isTotal = (eTop >= cTop && eBottom <= cBottom);
    var isPartial;

    if (partial === true) {
        isPartial = (eTop < cTop && eBottom > cTop) || (eBottom > cBottom && eTop < cBottom);
    } else if(typeof partial === "number"){
        if (eTop < cTop && eBottom > cTop) {
            isPartial = ((eBottom - cTop) * 100) / element.clientHeight > partial;
        } else if (eBottom > cBottom && eTop < cBottom){ 
            isPartial = ((cBottom - eTop) * 100) / element.clientHeight > partial;
        }
    }
    return (isTotal || isPartial);
}

答案 4 :(得分:1)

我能够通过对发布的纯JavaScript版本进行一些小改动来完成这项工作

@RunWith(SpringRunner.class)
@ContextConfiguration("classpath*:applicationContext-test.xml")
public class SomeBeanTest {
@Autowired
ApplicationContext ctx;
@Autowired
@Value("1")
private SomeBean someBean;

private SomeBean someBean2;

@Before
public void setUp() throws Exception {
    someBean2 = ctx.getBean(SomeBean.class, "2");
}

@Test
public void test() {
    System.out.println("test");
}
}

答案 5 :(得分:0)

我用最后一个答案制作了一个jquery插件:

(function($) {
    $.fn.reallyVisible = function(opt) {

        var options = $.extend({
            cssChanges:[
                { name : 'visibility', states : ['hidden','visible'] }
            ],
            childrenClass:'mentioners2',
            partialview : true
        }, opt);

        var container = $(this);
        var contHeight;
        var contTop;
        var contBottom;
        var _this = this;
        var _children;

        this.checkInView = function(elem,partial){

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

            var isTotal = (elemTop >= 0 && elemBottom <=contHeight);
            var isPart = ((elemTop < 0 && elemBottom > 0 ) || (elemTop > 0 && elemTop <= container.height())) && partial ;

            return  isTotal  || isPart ;
        }

        this.bind('restoreProperties',function(){
            $.each(_children,function(i,elem){
                $.each(options.cssChanges,function(i,_property){
                    $(elem).css(_property.name,_property.states[1]);        
                });
            });
            _children = null;
        });

        return this.each(function(){
            contHeight = container.height();
            contTop = container.scrollTop();
            contBottom = contTop + contHeight ;

            _children = container.children("."+options.childrenClass);

            $.each(_children,function(i,elem){
                var res = _this.checkInView(elem,options.partialview);
                if(  !res ){
                    $.each(options.cssChanges,function(i,_property){
                        $(elem).css(_property.name,_property.states[0]);        
                    });
                }
            });

        }); 
    }

})(jQuery);

答案 6 :(得分:0)

您可以尝试

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + window.innerHeight;
    var el = $(elem);
    var elemTop = el.offset().top;
    var elemBottom = elemTop + el.height();
    var elemDisplayNotNone = el.css("display") !== "none";

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

例如:

isScrolledIntoView('#button')

答案 7 :(得分:0)

出于我的目的玩它。这是我的解决方案(香草)

菜单是容器,el是活动元素。

const isVisible = (menu, el) => {
      const menuHeight = menu.offsetHeight;
      const menuScrollOffset = menu.scrollTop;
    
      const elemTop = el.offsetTop - menu.offsetTop;
      const elemBottom = elemTop + el.offsetHeight;
      return (elemTop >= menuScrollOffset &&
     elemBottom <= menuScrollOffset + menuHeight);
    }