美文网首页让前端飞Web前端之路
H5吸顶功能--划到某一元素处将其固定在顶部

H5吸顶功能--划到某一元素处将其固定在顶部

作者: 菜菜___ | 来源:发表于2020-06-16 16:08 被阅读0次

在网页里经常遇到这样的情况,滑动页面至某一个元素处,元素一直固定在顶部或底部,当页面滑到元素原有位置上方时,元素恢复原有位置。例如京东秒杀的活动时间,还有常见的搜索输入框固定在顶部。


利用js写了个搜索输入框固定在上方的例子,效果示例如下:

主要用到了offsetTop与scrollTop。
offsetTop:元素到其上级层顶部的距离.
scrollTop:网页被卷去的高

当网页滚动条卷起来的高度大于需要固定定位元素距离顶部的高时,就可以设置固定定位样式了。
代码如下:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0' />
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body{
            max-width: 750px;
            margin:0 auto;
        }
        .container ul{
            padding: 0 20px;
            list-style: none;
        }
        .container>img{
            width: 100%;
        }
        .container .input{
            padding: 0 10px;
        }
        .container .input input{
            width: 100%;
            border: 1px solid #d6d6d6;
            outline: none;
            height: 30px;
            border-radius: 10px;
        }
        .container ul li{
            margin-top: 50px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<div>
    <div class="container">
        <img src="top_banner.jpg"/>
        <div class="input" id="searchBar">
            <input type="text" />
        </div>
        <ul>
            <li>我是列表</li>
            <li>我是列表</li>
            <li>我是列表</li>
            <li>我是列表</li>
            <li>我是列表</li>
            <li>我是列表</li>
            <li>我是列表</li>
            <li>我是列表</li>
            <li>我是列表</li>
            <li>我是列表</li>
            <li>我是列表</li>
        </ul>
    </div>
</div>
<script type="text/javascript">
    window.onload=
            function(){
                var oDiv = document.getElementById("searchBar"),
                        H = 0,
                        Y = oDiv
                while (Y) {
                    H += Y.offsetTop;
                    Y = Y.offsetParent;
                }
                window.onscroll = function()
                {
                    var s = document.body.scrollTop || document.documentElement.scrollTop;
                    if(s>H) {
                        oDiv.style = "position:fixed;top:0;left:0;right:0;"
                    } else {
                        oDiv.style = ""
                    }
                }
            }
</script>
</body>

原文作者技术博客:https://www.jianshu.com/u/ac4daaeecdfe

相关文章

网友评论

    本文标题:H5吸顶功能--划到某一元素处将其固定在顶部

    本文链接:https://www.haomeiwen.com/subject/jqubzhtx.html