页面滚动,菜单栏悬停怎么实现?

如图

clipboard.png

当往上滚动,菜单栏滚动到顶部的位置时,再继续滚动,悬停在顶部。
问:
1、Vue是否有提供这样的控件?
2、如果vue没有,有什么现成的一些轮子吗?(最好兼容性好一点,webapp)
3、如果现成的轮子也没有,怎么实现?

如上,有没有大佬解答下,不胜感激

按照 @游龙翔隼的思路已解决,贴上代码:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="css/style.css" rel="stylesheet">
    </head>
    <body>
        <div style="overflow:scroll">
            <div style="width: 100%;height:100px;background:red;margin-bottom:10px"></div>
            <div id="bar" style="width:100%;height:20px;background:black"></div>
            <div style="width: 100%;height:1500px;background:red;margin-top:10px"></div>
        </div>
    </body>
    <script>
        var barOffSetTop = document.getElementById('bar').offsetTop;

        window.addEventListener('scroll', (e) => {
            if(barOffSetTop < document.body.scrollTop){
                bar.classList.add('add-fixed')
            }else{
                bar.classList.remove('add-fixed')
            }
        });
    </script>
</html>
<style>
    .add-fixed{
        position: fixed;
        top: 0;
    }
</style>

注意:菜单栏的offsetTop不能动态取,不然置顶后offsetTop的值就改变了,滑动回来的时候,菜单栏无法复位。

阅读 6.2k
4 个回答
position: sticky

用sticky定位就行了,具体看 这里 注:目前兼容性较差

之前也做过类似的东西,实现比较简单,来说下思路:
1.监听滚动事件
2.判断菜单dom是否超出视窗
3.超出后使用绝对定位,你这里应该用fixed吧,固定在顶部

需要监听滚动,当滚动到你想要的位置时,把那个需要固定的元素dom拷贝一份出来,然后fixed,此时需要把之前那个dom隐藏起来(visibiliy:hidden);依次判断,当滚动到需要位置时,再把这个copy的dom隐藏起来,把之前的显示出来。。。

代码仅供参考

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
div{width:800px;}
#head{height:200px; background:#CC6699; z-index:1; position:absolute;}
#body{background:#FFCC99; height:500px; padding-top:200px;}
#foot{height:500px; background:#CCFFFF;}
</style>
</head>
<body>
    <div id="head">head</div>
    <div id="body">body</div>
    <div id="foot">foot</div>
</body>
</html>
<script type="text/javascript">
    var head = document.getElementById("head");
    var bodyHeight = document.getElementById("body").offsetHeight;
    var foot = document.getElementById("foot");
    var footHeight = foot.offsetHeight;
    window.onscroll = function() {
        var t = document.documentElement.scrollTop || document.body.scrollTop;
        if (t < 150) return; // 150 自行修改,就是你说的 offsetTop 吧(?)
        if (t > 150 && t < (bodyHeight - window.innerHeight + 160)) { // 160 是我自己的另一个数值,无视即可
            head.style.top = t - 150;
        }
    }
</script>
新手上路,请多包涵

fixed 在ios 端 兼容性很差 楼主怎么整的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题