页面滚动到某个Div的位置时该Div fixed

2018-07-31  本文已影响0人  亲亲美人鱼1

写在前面

页面交互中经常会有这样的需求:随着滚动条的滚动,当某个包含重要信息的元素不在当前视野范围内时,我们需要fixed到页面上方或者底部,有一种简单的实现方法,不用关注文档高度,不用计算滚动条的卷曲的高度,使用getBoundingClientRect()提供的信息来实现。

element.getBoundingClientRect方法
  1. 先看返回值
    document.getElementsByClassName('priceFixedOuter')[0].getBoundingClientRect();
    返回值如下:
  2. 简单说明

返回值中除了width和height之外其他的属性值都是相对于视窗左上角来说的。与滚动条的位置有关系。当滚动条的位置发生变化时,这些值会跟着发生变化。

fixed效果方法实现举例
// 该例子是当滚动条滚动到能看到定制总价容器时,隐藏定制总价fixed容器。
// ⚠️定制总价容器和定制总价fixed容器为两个容器。
var $fixedPriceWrap = $('.priceFixedOuter'); // 定制总价fixed容器
var $priceWrap = $('.submitWrap'); // 定制总价容器
var priceWrap = $priceWrap[0];
var winHeight = $(window).height(); // 可视窗口的高度

// 滚动条滚动到底部能看到定制总价时,隐藏总价fixed.
$(window).on('scroll', function () {
    var priceWrapTop = priceWrap.getBoundingClientRect().top; // 定制总价容器顶部距离窗口的高度
    if (priceWrapTop - winHeight < 0) {
        $fixedPriceWrap.hide();
    } else {
        $fixedPriceWrap.show();
    }
});

写在最后

几个高度
  1. 文档高度
    Math.max(document.documentElement.clientHeight, document.body.clientHeight);
  2. 滚动条卷去的高度
    Math.max(document.documentElement.scrollTop, document.body.scrollTop);
上一篇 下一篇

猜你喜欢

热点阅读