CSS局部滚动

861 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

一.简单说明使用CSS自定义变量

1.1. 声明一个自定义属性,属性名需要以两个减号(--)开始,下面是定义的局部CSS变量

/* 局部CSS变量 */
.element{
  --header-height: 50px;
  --player-height: 300px;
  --title-height: 50px;
}

1.2. 这是定义的全局CSS变量, 其中:root是根伪类,是表示 元素

/* 全局CSS变量 */
:root {
  --header-height: 50px;
  --player-height: 300px;
  --title-height: 50px;
}

1.3. calc 的CSS计算函数可以配合CSS变量使用,而var()是读取CSS变量的值

  • +加法
  • -减法
  • *乘法,乘数中至少有一个是 number
  • /除法,除数(/ 右面的数)必须是 number
:root{
  --header-height: 50px;
  --player-height: 300px;
  --title-height: 50px;
  --list-top: calc(var(--header-height) + var(--player-height) + var(--title-height));
}

1.4. 如果使用SCSS里的变量计算则是这样写

$header-height: 50px;
$player-height: 300px;
$title-height: 50px;
$list-top: calc(#{$header-height} + #{$player-height} + #{$title-height});

二.整体结构代码

<body>
  <div id="app">
    <div class="header">{{header}}</div>
    <div class="player"></div>
    <div class="title">{{title}}</div>
    <div class="list-wrapper">
      <ul class="list">
        <li class="item" v-for="(item,index) in list" :key="index">{{item}}</li>
      </ul>
    </div>
  </div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
let app = new Vue({
  el: '#app',
  data(){
    return {
      header: "标题栏",
      title: "当前选项",
      list: [0,1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8],
    }
  }
});
</script>

三.设置样式

3.1. 将app样式设置 position: relative;

3.2. 再将滚动列表外层设置position: absolute;

3.3. top设置全局变量计算得到的--list-top,高度则用100vh - var(--list-top)就是它的高度

3.4. 最后设置滚动条样式取消

:root {
  --header-height: 50px;
  --player-height: 300px;
  --title-height: 50px;
  --list-top: calc(var(--header-height) + var(--player-height) + var(--title-height));
}
*{
  padding: 0;
  margin: 0;
  font-size: 0;
  font-family: 'Microsoft Yvar()aHei';
  text-decoration: none;
}
#app{
  position: relative;
}
.header{
  width: 100%;
  height: var(--header-height);
  line-height: var(--header-height);   
  font-size: 16px;
  text-align: center;
  background: #9ca8ac;   
}
.player{
  width: 100%;
  height: var(--player-height);
  line-height: var(--player-height);   
  text-align: center;
  background: rgb(190, 190, 147); 
}
.title{
  width: 100%;
  height: var(--title-height);
  line-height: var(--title-height);
  font-size: 16px;   
  text-align: left;
  background: rgb(143, 143, 142); 
}
.list-wrapper{
  width: 100%;
  height: calc(100vh - var(--list-top));
  position: absolute;
  top: var(--list-top);
  left: 0;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  /* 隐藏滚动条 */
  overflow: -moz-scrollbars-none;  /* Firefox */ 
  -ms-overflow-style: none;        /* IE 10+ */
}
.list-wrapper::-webkit-scrollbar { 
  display: none; /* chrome */
}
.item{
  width: 100%;
  height: 50px;
  background: #9ca8ac;
  line-height: 50px;
  color: black;
  font-size: 16px;
}