顶部悬浮效果

最终样式
在这里插入图片描述
所用知识点:
dom知识点:

可视宽,高 document.documentElement.clientWidth / document.documentElement.clientHeight
实际宽,高 document.documentElement.scrollWidth/document.documentElement.scrollHeight
滚动条距离上,左边的距离 document.documentElement.scrollTop/document.documentElement.scrollLeft

元素样式宽,高 width / height
元素内容宽,高 ele.clientWidth / ele.clientHeight padding+width / padding+height
实际宽,高 ele.offsetWidth / ele.offsetHeight padding+border+width /padding+border+height
相对父元素的距离 ele.offsetTop / ele.offsetLeft

DOM样式:
ele.style.property=value
property(属性)内的值不支持-,当出现-时,将其去掉,并采用驼峰命名法,例font-size为fontSize

代码:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>29练习2_顶部悬浮</title>
  <style>
    * {
      padding: 0;
      margin: 0;
      font-size: 18px;
    }

    body {
      height: 3000px;
    }

    .top {
      height: 600px;
      display: flex;
      align-items: stretch;
      justify-content: center;
      background: yellow;
    }

    .container {
      display: flex;
    }

    .left {
      background: green;
      height: 300px;
      width: calc(100% - 300px);
    }

    .right {
      width: 300px;
      height: 300px;
      background: pink;
    }
  </style>
</head>

<body>
  <div id="topContent" class="top">
    我是上部内容
  </div>
  <div class="container">
    <div class="left">
      我是左侧内容
    </div>
    <div id="right" class="right">
      我是右侧内容
    </div>
  </div>
</body>
<script>

  var oTop = document.querySelector('.top');
  var oRight = document.querySelector('.right');
  //窗口的滚动条滚动时触发此事件
  window.onscroll = function () {
    //解决IE浏览器的兼容问题
    var root = document.documentElement || document.body;
    //root.scrollTop 为滚动条相对于文档上方的高度,oTop.offsetHeight为oTop该元素的实际高度
    //若滚动条滚动高度大于等于oTop元素的实际高度是触发此事件
    if (root.scrollTop >= oTop.offsetHeight) {
      //对oRight事件进行绝对定位
      oRight.style.position = 'fixed';
      oRight.style.right = '0px';
      oRight.style.top = '0px';
    } else {
      //对oRight事件回复原值
      oRight.style.position = 'initial';
      oRight.style.right = 'initial';
      oRight.style.top = 'initial';
    }
  }

</script>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值