滚动高度和位置

滚动高度

window.innerHeight 当前可视区域的高度
onscroll  窗口滚动事件
window.onscroll = function () {}

已滚动的距离

document.documentElement.scrollTop
document.body.scrollTop  (ie)

解决兼容性问题

var st = document.documentElement.scrollTop || document.body.scrollTop;

已滚动的宽度的距离

 var sl = document.documentElement.scrollLeft || document.body.scrollLeft;
console.log(sl);

滚动元素的总高度

document.documentElement.scrollHeight 

滚动元素的总宽度

 document.documentElement.scrollWidth);

滚动到指定位置

document.documentElement.scrollTop = 1000;
document.documentElement.scrollLeft = 1000;
或
document.documentElement.scrollTo(1000, 1000)  x,y

scrollBy 根据当前位置,增加或者减少指定的距离

document.documentElement.scrollBy(-100, -100);

scrollIntoView();

scrollIntoView();
不写参数时,默认为true  当前元素顶部与可视区域顶部对齐
​
scrollIntoView(false);
为false时,当前元素的底部与可视区域的底部对齐

回到顶部案例

 window.onscroll = function() {
            console.log(document.documentElement.scrollHeight);
var st = document.documentElement.scrollTop || document.body.scrollTop;
var sh = document.documentElement.scrollHeight;
​
// 已滚动距离不包括当前可视窗口的高度
// window.innerHeight 当前可视区域的高度
// 已滚动距离 > 总高度 - 可视区域高度 - 400
console.log(st, window.innerHeight);
if (st >= sh - window.innerHeight - 400) {
        back.style.display = 'block';
        } else {
                back.style.display = 'none';
         }
      }
​
已滚动距离document.documentElement.scrollTop || document.body.scrollTop
总高度document.documentElement.scrollHeight
可视区域高度window.innerHeight
'400' 指到距离底部400显示

元素偏移量

 <div id="outer">
        <div id="inner"></div>
 </div>
​
 console.log(inner.offsetTop, inner.offsetLeft);

offsetTop 就是该元素顶部到整个页面的顶部

如果该元素的父元素有定位,则是该元素顶部到父元素顶部的距离

如如果该元素有fixed定位,则是该元素到浏览器可视窗口顶部的距离

console.log(inner.offsetParent);

如果上级元素没有设置position: static以外的值 返回的是body

如果上级元素设置了position: static以外的值 是最近的设置了position的上级元素

如果inner设置了position: fixed null

元素占位宽高

box.offsetWidth, box.offsetHeight

获取元素的宽高 元素内容溢出不管 包括border、padding、内容区

box.clientWidth, box.clientHeight

获取元素的宽高 元素内容溢出不管 包括padding、内容区

固定导航栏案例

 <div class="head"></div>
加box的原因:没有父元素的话,给nav添加fixed之后,offsetTop会变成0,判断就会出现问题 
加上父元素之后,让父元素一直占位,用父元素的offsetTop去对比判断
 <div id="box">
        <div id="nav">导航栏</div>
 </div>
 <script>
     var nav = document.getElementById('nav');
     var box = document.getElementById('box');
​
      window.onscroll = function () {
// 判断已滚动的距离大于等于导航栏到页面顶部的距离时,让nav固定到浏览器可视区域的顶部
       if (document.documentElement.scrollTop >= box.offsetTop) {
          nav.style.position = 'fixed';
          nav.style.top = 0;
         } else {
          console.log(111);
        nav.style.position = 'static';
            }
        }
 </script>
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值