css篇(003)——移动端吸顶效果

3,350 阅读2分钟

前言

在最近做的移动端项目开发过程中,交互老师要求做一个播放器在滚动过程中吸顶效果,当时第一反应还会使用js的scroll来做这种交互,但是同事说有css属性sticky也可以实现吸顶效果,最终项目使用的是css的粘性定位sticky来写,基于此,记录下实现吸顶效果的两种方式。

第一种方法、css粘性定位

sticky属性功能描述:基于用户的滚动位置来定位,sticky 定位的元素位置在 position:relative 与 position:fixed 定位之间切换,具体取决于滚动位置。它的行为就像 position:relative; 而当页面滚动超出目标区域时,它的表现就像 position:fixed;,它会固定在目标位置。 元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。这个特定阈值就是指top、right、 bottom、left四个值之一,只有指定这四个值其中之一,粘性定位才能生效。否则其表现与相对定位表现一致。

DEMO

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
    header{
         height: 150px;
         background-color: green;
    }
    .targetBox{
         width: 100%;
         height: 50px;
         background-color: #2aabd2;
        position: -webkit-sticky;
        position: sticky;
        top: 0;
    }
    footer{
        width:1200px;
        height: 1200px;
        background-color: #666666;
        margin:0px auto;
    }
    </style>
</head>
<body>
    <header></header>
    <div class="targetBox">
        sticky元素,吸顶元素
    </div>
    <footer></footer>
    
</body>
</html>

注意

  • 父元素不能overflow:hidden或者overflow:auto属性;
  • 必须指定top、bottom、left、right4个值之一,否则只会处于相对定位
  • 父元素的高度不能低于sticky元素的高度
  • sticky元素仅在其父元素内生效

兼容性

Internet Explorer, Edge 15 及更早 IE 版本不支持 sticky 定位。 Safari 需要使用 -webkit- prefix

第二种方法、通过监听滚动条滚动事件 onscroll 实现

这种方式 使用js 事件监听滚动条滚动动的距离 手动设置吸顶元素position:fixed 实现。

使用 document.body.scrollTop; 得到滚动条距离顶部的高, 判断超过偏移区域是 手动加入position:fixed ; top:0px ;

DEMO

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
    .main{
         position: relative;
    }
    header{
         height: 150px;
         background-color: green;
    }
    .targetBox{
         width: 100%;
         height: 50px;
         background-color: #2aabd2;
    }
    footer{
        width:1200px;
        height: 1200px;
        background-color: #666666;
        margin:0px auto;
    }

    </style>

</head>
<body>
    <div class="main">
        <header></header>
        <div class="targetBox">
            吸顶元素
        </div>
        <footer></footer>
    </div>
    
</body>
<script>
var targetBox=document.querySelector(".targetBox");
function stickyTarget(){
    if(document.documentElement.scrollTop >= 150){
        targetBox.style.position="fixed";
        targetBox.style.top="0px";
        targetBox.style.zIndex="2";
    }else{
        targetBox.style.position="relative";
    }
}
window.addEventListener( 'scroll' , stickyTarget);

</script>
</html>