元素随滚动条滚动后固定在某个地方

元素随滚动条滚动后固定在某个地方_第1张图片

  1. 先让整体布局居中,左边main内容区域块级设置margin-right来腾出右边的位置,右边sider使用绝对定位黏在父元素上面,
  2. sider中仍然按正常布局,当被卷去的高度大于tip距离网页顶部的宽度时,给sider加一个sticky的class,这样tip就变成固定定位了
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <style>
        * {
            margin: 0;
        }

        .container {
            width: 1050px;
            height: 1600px;
            margin: 0 auto;
            position: relative;
        }
        
        .main {
            margin-right: 280px;
            height: 1600px;
            background-color: pink;
        }

        .sider {
            position: absolute;
            top: 0;
            right: 0;
            width: 270px;
            background-color: #bfa;
        }

        .info {
            height: 400px;
            background-color: cyan;
            margin-bottom: 10px;
        }

        .tip {
            width: 270px;
            height: 200px;
            background-color: skyblue;
        }

        .sticky .tip {
            position: fixed;
            top: 10px;
        }
        
    style>
head>
<body>
    <div class="container">
        <div class="main">div>
        <div class="sider " id="sider"> 
            <div class="info">div>
            <div class="tip" id="tip">

            div>
        div>
    div>
    <script>
        let sider = document.getElementById('sider')
        /* let sider = document.getElementById('sider')
        sider.classList.add('sticky') */
        var tip = document.getElementById('tip')
        let tipOffsetTop = tip.offsetTop
        console.log(tipOffsetTop);

        window.addEventListener('scroll', function(){
            // console.log(document.body.scrollTop+document.documentElement.scrollTop);
            // console.log(tip.offsetTop);
            let scrolledValue = document.body.scrollTop+document.documentElement.scrollTop
            if(scrolledValue >= tipOffsetTop - 10) {
                sider.classList.add('sticky')
            } else {
                sider.classList.remove('sticky')
            }

			if(!scroll) {
                scroll = scrolledValue
            } else {
                if(scroll - scrolledValue > 0) {
                    console.log('鼠标向上滚动');
                } else {
                    console.log('鼠标向下滚动');
                }
                scroll = scrolledValue
            }
        })
    script>
body>
html>

你可能感兴趣的:(前端学习,css,css3,前端)