list之flex布局写法

list之flex布局写法

list之flex布局写法

移动端实际场景中经常会遇到将header置顶,然后下面list需要滚动的情况,通常的做法会是将header使用fixed的方式固定到顶部,然后list主体相对于header的位置设置marginTop或者position的定位,这样的话做起来感觉有点别扭,也不贴合移动端的布局,而且position:fixed定位会在IOS8以下发生抖动现象,所以使用flex布局最佳。
如果要禁用IOS的橡皮筋效果,可以使用下面橡皮筋禁止方法,也可以借用[inobounce](https://github.com/lazd/iNoBounce)库处理。
.root的样式设置也可以替换为html和body设置height: 100%的方式处理,少写一个div标签,但是个人觉得这样的处理直接动html根标签不太合适,而且可控性不好,所以没有写出来。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.root {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.flexbox {
display: flex;
flex-direction: column;
height: 100%;
}
header,
footer {
text-align: center;
background-color: lightblue;
}
section {
flex: 1;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
section div:nth-of-type(2n) {
background-color: lightcyan;
}
</style>
</head>
<body>
<div class="root">
<div class="flexbox">
<header>Header</header>
<section id="scroller">
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</section>
<footer>Footer</footer>
</div>
</div>
<script>
// 橡皮筋禁止效果
let startY;
const scroller = document.getElementById('scroller');
document.addEventListener('touchstart', e => {
startY = e.touches[0].pageY;
});
document.addEventListener('touchmove', e => {
const endY = e.touches[0].pageY;
// 顶端不下滑
if (endY > startY && scroller.scrollTop === 0) {
e.preventDefault();
}
// 底端不上滑
if (endY < startY && scroller.scrollHeight - scroller.clientHeight === scroller.scrollTop) {
e.preventDefault();
}
}, {passive: false}); // 加passive是为了兼容部分IOS
</script>
</body>
</html>
05-11 13:40