如何检查元素是否靠近屏幕底部?

时间:2017-02-08 11:06:20

标签: javascript jquery html css

如何检查某些元素是否靠近屏幕底部让我们从底部说100px? (不是页面底部)。

我想要的是,当点击这个元素时,另一个元素会显示出来,如果靠近屏幕底部,它会滑到顶部而不是向下滑动?

2 个答案:

答案 0 :(得分:0)

我认为您想要的是当用户几乎位于屏幕底部时显示的按钮,当用户点击它时,它会将它们滚动回屏幕顶部。

您可能希望使用JavaScript来实现此目标。

使用jQuery

<script type="text/javascript>
    $(document).scroll(function(){
        var x = $(this).scrollTop();
        if (x > 250) //The 250 is the total height of div that the user scrolls to before the button displys for the user to click
        {
            $('.button').fadeIn();
        } else {
            $('.button').fadeOut();
        }

        $('.button').click(function() {
        $('html, body').animate({
            scrollTop: $('.topmost_div').offset().top}, 'slow'); //tell the page to scroll back to the div at the top of the page.
        });
    });
</script>

希望这会有所帮助

答案 1 :(得分:0)

您可以使用以下条件识别元素在屏幕底部100px以下的时间(无需使用jQuery):

if (window.innerHeight - element.getBoundingClientRect().bottom < 100){
  // the desired place
}
相关问题