如何知道元素在屏幕上是否可见.如果没有,请滚动页面

How to know if an element is visible on the screen. If not, scroll the page

本文关键字:如果没有 滚动 元素 何知道 屏幕 是否      更新时间:2023-09-26


我正在尝试建立一个弹出窗口,就像这里的那个。在这种情况下,当我单击CUSTOMISE按钮时,按钮下方会出现一个窗口。如果元素在屏幕上不完全可见,则页面向下或向上滚动,直到完全可见

我能够达到一半的结果:

$('body').on('click',"#"+ID,function () {
        var $this = $(this);
        $('#attr-div-'+baseId).css({
            top: $this.position().top+55,
        }).show();
    });

如何滚动页面,直到元素完全可见?谢谢

这样的东西应该有效,但对更大的想法进行篡改会有所帮助:

$('body').on('click', "#"+ID, function() {
    var popup = $('#attr-div-'+baseId);
    var offset = $(this).offset().top+55;
    popup.css('top', offset).show();
    $(window).scrollTop(offset+popup.height()-$(this).height());
});

假设它没有固定的位置——如果它在窗户下面,你就必须重新定位。

它可以被细化(当然也可以动画化,而不是即时的):

http://codepen.io/anon/pen/dPBNWY?editors=001

我找到了解决方案:

$('body').on('click',"#"+ID,function () {
        var $this = $(this);
        $('#attr-div-'+baseId).css({
            top: $this.position().top+55,
        }).show();
        $('html, body').animate({
            scrollTop: $('#attr-div-'+baseId).offset().top-55
        }, 1000);
    });

这并不完全是我想要的,但它允许我使弹出窗口始终可见。