如果元素不可见则滚动 [英] Scroll if element is not visible

查看:161
本文介绍了如果元素不可见则滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how to determine, using jquery, if the element is visible on the current page view. I'd like to add a comment functionality, which works like in facebook, where you only scroll to element if it's not currently visible. By visible, I mean that it is not in the current page view, but you can scroll to the element.

推荐答案

现场演示

Live Demo

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

Basically you just check the position of the element to see if its within the windows viewport.

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;
}

这篇关于如果元素不可见则滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆