如果元素不可见则滚动

时间:2011-06-02 14:19:43

标签: javascript jquery scroll viewport visible

如何使用jquery确定元素在当前页面视图中是否可见。我想添加一个评论功能,就像在facebook中一样,只有在当前不可见时才滚动到元素。通过可见,我的意思是它不在当前页面视图中,但您可以滚动到元素。

9 个答案:

答案 0 :(得分:37)

<强> Live Demo

基本上你只需要检查元素的位置,看它是否在windows视口中。

function checkIfInView(element){
    var offset = element.offset().top - $(window).scrollTop();

    if(offset > window.innerHeight){
        // Not in view so scroll to it
        $('html,body').animate({scrollTop: offset}, 1000);
        return false;
    }
   return true;
}

答案 1 :(得分:11)

改善Loktar的答案,修正以下内容:

  1. 向上滚动
  2. 滚动到display:none元素(如隐藏的div等)

    function scrollToView(element){
        var offset = element.offset().top;
        if(!element.is(":visible")) {
            element.css({"visibility":"hidden"}).show();
            var offset = element.offset().top;
            element.css({"visibility":"", "display":""});
        }
    
        var visible_area_start = $(window).scrollTop();
        var visible_area_end = visible_area_start + window.innerHeight;
    
        if(offset < visible_area_start || offset > visible_area_end){
             // Not in view so scroll to it
             $('html,body').animate({scrollTop: offset - window.innerHeight/3}, 1000);
             return false;
        }
        return true;
    }
    

答案 2 :(得分:5)

我做了一个稍微更通用的digitalPBK答案版本,它最小程度地滚动div或其他容器(包括正文)中包含的元素。只要元素以某种方式包含在父元素中,您就可以将DOM元素或选择器传递给函数。

function scrollToView(element, parent) {
    element = $(element);
    parent = $(parent);

    var offset = element.offset().top + parent.scrollTop();

    var height = element.innerHeight();
    var offset_end = offset + height;
    if (!element.is(":visible")) {
        element.css({"visibility":"hidden"}).show();
        var offset = element.offset().top;
        element.css({"visibility":"", "display":""});
    }

    var visible_area_start = parent.scrollTop();
    var visible_area_end = visible_area_start + parent.innerHeight();

    if (offset-height < visible_area_start) {
        parent.animate({scrollTop: offset-height}, 600);
        return false;
    } else if (offset_end > visible_area_end) {
        parent.animate({scrollTop: parent.scrollTop()+ offset_end - visible_area_end }, 600);
        return false;

    }
    return true;
}

答案 3 :(得分:5)

在尝试了所有这些解决方案之后,还有更多的解决方案,它们都不能满足我在IE11中运行旧的门户网站软件(10年)的要求(在一些兼容模式下)。他们都无法正确确定元素是否可见。但是我找到了solution。我希望它有所帮助。

function scrollIntoViewIfOutOfView(el) {
    var topOfPage = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
    var heightOfPage = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    var elY = 0;
    var elH = 0;
    if (document.layers) { // NS4
        elY = el.y;
        elH = el.height;
    }
    else {
        for(var p=el; p&&p.tagName!='BODY'; p=p.offsetParent){
            elY += p.offsetTop;
        }
        elH = el.offsetHeight;
    }
    if ((topOfPage + heightOfPage) < (elY + elH)) {
        el.scrollIntoView(false);
    }
    else if (elY < topOfPage) {
        el.scrollIntoView(true);
    }
}

答案 4 :(得分:3)

你可以看看他在jQuery Cookbook中的精彩链接:

Determining Whether an Element Is Within the Viewport

测试视口中是否包含元素

jQuery(document).ready(function() {
    var viewportWidth = jQuery(window).width(),
        viewportHeight = jQuery(window).height(),
        documentScrollTop = jQuery(document).scrollTop(),
        documentScrollLeft = jQuery(document).scrollLeft(),

        $myElement = jQuery('#myElement'),

        elementOffset = $myElement.offset(),
        elementHeight = $myElement.height(),
        elementWidth = $myElement.width(),

        minTop = documentScrollTop,
        maxTop = documentScrollTop + viewportHeight,
        minLeft = documentScrollLeft,
        maxLeft = documentScrollLeft + viewportWidth;

    if (
        (elementOffset.top > minTop && elementOffset.top + elementHeight < maxTop) &&
        (elementOffset.left > minLeft && elementOffset.left + elementWidth < maxLeft)
    ) {
        alert('entire element is visible');
    } else {
        alert('entire element is not visible');
    }
});

测试可见元素的数量

jQuery(document).ready(function() {

var viewportWidth = jQuery(window).width(),
    viewportHeight = jQuery(window).height(),

    documentScrollTop = jQuery(document).scrollTop(),
    documentScrollLeft = jQuery(document).scrollLeft(),

    $myElement = jQuery('#myElement'),

    verticalVisible, horizontalVisible,

    elementOffset = $myElement.offset(),
    elementHeight = $myElement.height(),
    elementWidth = $myElement.width(),

    minTop = documentScrollTop,
    maxTop = documentScrollTop + viewportHeight,
    minLeft = documentScrollLeft,
    maxLeft = documentScrollLeft + viewportWidth;

function scrollToPosition(position) {
    jQuery('html,body').animate({
        scrollTop : position.top,
        scrollLeft : position.left
    }, 300);
}

if (
    ((elementOffset.top > minTop && elementOffset.top < maxTop) ||
    (elementOffset.top + elementHeight > minTop && elementOffset.top + 
elementHeight < maxTop))
&&  ((elementOffset.left > minLeft && elementOffset.left < maxLeft) ||
    (elementOffset.left + elementWidth > minLeft && elementOffset.left +
elementWidth < maxLeft)))
{
    alert('some portion of the element is visible');

    if (elementOffset.top >= minTop && elementOffset.top + elementHeight 
<= maxTop) {
        verticalVisible = elementHeight;
    } else if (elementOffset.top < minTop) {
        verticalVisible = elementHeight - (minTop - elementOffset.top);
    } else {
        verticalVisible = maxTop - elementOffset.top;
    }

    if (elementOffset.left >= minLeft && elementOffset.left + elementWidth 
<= maxLeft) {
        horizontalVisible = elementWidth;
    } else if (elementOffset.left < minLeft) {
        horizontalVisible = elementWidth - (minLeft - elementOffset.left);
    } else {
        horizontalVisible = maxLeft - elementOffset.left;
    }

    var percentVerticalVisible = (verticalVisible / elementHeight) * 100;
    var percentHorizontalVisible = (horizontalVisible / elementWidth) * 100;

    if (percentVerticalVisible < 50 || percentHorizontalVisible < 50) {
        alert('less than 50% of element visible; scrolling');
        scrollToPosition(elementOffset);
    } else {
        alert('enough of the element is visible that there is no need to scroll');
    }

} else {
    // element is not visible; scroll to it
    alert('element is not visible; scrolling');
    scrollToPosition(elementOffset);
}

答案 5 :(得分:1)

以下代码帮助我实现了结果

function scroll_to_element_if_not_inside_view(element){
  if($(window).scrollTop() > element.offset().top){
    $('html, body').animate( { scrollTop: element.offset().top }, {duration: 400 } );
  }
}

答案 6 :(得分:0)

jQuery plugin允许我们快速检查整个元素(或者也只是其中的一部分)是否在浏览器可视视口内,而不管窗口滚动位置如何。您需要从GitHub repository

下载它

假设有以下HTML,并且您希望在页脚可见时发出警报:

<section id="container">
    <aside id="sidebar">
        <p>
            Scroll up and down to alert the footer visibility by color:
        </p>
        <ul>
            <li><span class="blue">Blue</span> = footer <u>not visible</u>;</li>
            <li><span class="yellow">Yellow</span> = footer <u>visible</u>;</li>
        </ul>
        <span id="alert"></span>
    </aside>
    <section id="main_content"></section>
</section>
<footer id="page_footer"></footer>

因此,在body标签关闭之前添加插件:

<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/jquery_visible/examples/js/jq.visible.js"></script>

之后你可以用这样简单的方式使用它:

<script type="text/javascript">
jQuery( document ).ready(function ( $ ) {
  if ($("footer#page_footer").visible(true, false, "both")) {
    $("#main_content").css({"background-color":"#ffeb3b"});
    $("span#alert").html("Footer visible");
  } else {
    $("#main_content").css({"background-color":"#4aafba"});
    $("span#alert").html("Footer not visible");
  }

  $(window).scroll(function() {
    if ($("footer#page_footer").visible(true, false, "both")) {
      $("#main_content").css({"background-color":"#ffeb3b"});
      $("span#alert").html("Footer visible");
    } else {
      $("#main_content").css({"background-color":"#4aafba"});
      $("span#alert").html("Footer not visible");
    }
  });
});
</script>

这是demo

答案 7 :(得分:0)

无jQuery版本。

这里的特殊情况是滚动容器是TBODY的主体(table.bodyTABLE)(独立于THEAD滚动)。但是它可以适应任何情况,更简单一些。

const row = table.body.children[ ... ];
...

const bottomOfRow = row.offsetHeight + row.offsetTop ;
// if the bottom of the row is in the viewport...
if( bottomOfRow - table.body.scrollTop < table.body.clientHeight ){
    // ... if the top of the row is in the viewport
    if( row.offsetTop - table.body.scrollTop > 0 ){
        console.log( 'row is entirely visible' );
    }
    else if( row.offsetTop - table.body.scrollTop + row.offsetHeight > 0 ){
        console.log( 'row is partly visible at top')
        row.scrollIntoView();
    }
    else {
        console.log( 'top of row out of view above viewport')
        row.scrollIntoView();
    }
}
else if( row.offsetTop  - table.body.scrollTop < table.body.clientHeight ){
    console.log( 'row is partly visible at bottom')
    row.scrollIntoView();
}
else {
    console.log( 'row is out of view beneath viewport')
    row.scrollIntoView();
}

答案 8 :(得分:0)

我认为这是完整的答案。 电梯必须能够上下移动;)

function ensureVisible(elementId, top = 0 /* set to "top-nav" Height (if you have)*/) {
  let elem = $('#elementId');
  if (elem) {
    let offset = elem.offset().top - $(window).scrollTop();
    if (offset > window.innerHeight) { // Not in view
      $('html,body').animate({ scrollTop: offset + top }, 1000);
    } else if (offset < top) { // Should go to top
      $('html,body').animate({ scrollTop: $(window).scrollTop() - (top - offset) }, 1000);
    }
  }
}