【问题标题】:Fix content than scroll when user is near the end of the page当用户接近页面末尾时,修复内容而不是滚动
【发布时间】:2015-07-01 13:54:23
【问题描述】:

这里有点谜。

我有一个 div,我想一直在屏幕上显示。我使用以下 CSS:

<style>
    .f {position: fixed;
     bottom:0px
     align:center;
     }
</style>

我试图弄清楚如何将其固定在屏幕底部直到距离末尾 200px 我希望它与页面一起滚动然后当用户滚动到底部时它将是距离底部 200px页面。

任何帮助将不胜感激

【问题讨论】:

  • 创建一个fiddle你所期望的,并发布一些html
  • 我已经编辑了很多次我的答案,但这次应该没有错误和一个有效的 jsfiddle 示例。很难用简短的语言来解释我们所做的数学运算。如果有什么不清楚的地方,请随时提问!

标签: jquery html css scroll


【解决方案1】:

让我们做一个基本的构建:

<div id="content">Content to be scrolled as Wrapper </div>
<div id="mydiv" class="fixed"> Div that should be fixed </div>
<div id="end"> Everything after the fixed div </div>

我们使用.fixed 类快速修复底部的div,以便我们可以使用.addClass('fixed').removeClass('fixed') 切换一些css 属性。

.fixed {
   position: fixed;
   bottom: 0;
}

所以有这个.scrollTop 函数,它允许我们从顶部到底部滚动一定数量的像素。这正是您所需要的。诀窍是要知道固定元素应该从顶部开始随着内容滚动多少像素。

让我们做一些 jQuery 来找出答案:

// Create function to add/remove Class if .scrollTop
$.fn.followTo = function (pos) {
    var $this = this,
        $window = $(window);

    $window.scroll(function (e) {
        if ($window.scrollTop() < pos) {
            $this.addClass('fixed');
        } else {
            $this.removeClass('fixed');
        }
    });
};

var $height_content = $('#content').outerHeight(); //get height of content
var $height_div = $('#mydiv').outerHeight(); //get height of fixed div
var $height_viewport = $(window).height(); //get height of viewport
var $fixed_till = ($height_content + $height_div - $height_viewport);

// Use function created above like so:
// $('selector').followTo( /* height from top in px */ );
$('#mydiv').followTo($fixed_till);

检查DEMO ON JSFIDDLE

【讨论】:

    猜你喜欢
    • 2012-05-26
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2021-10-17
    相关资源
    最近更新 更多