position属性sticky

在目标区域以内,它的行为就像 position:relative; 而当页面滚动超出目标区域时,它的表现就像 position:fixed;,它会固定在目标位置。

元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。

这个特定阈值指的是 top, right, bottom 或 left 之一,换言之,指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。

例子

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title></title> 
<style>
div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  padding: 5px;
  background-color: #cae8ca;
  border: 2px solid #4CAF50;
}
</style>
</head>
<body>

<p>尝试滚动页面。</p>
<p>注意: IE/Edge 15 及更早 IE 版本不支持 sticky 属性。</p>

<div class="sticky">我是粘性定位!</div>

<div style="padding-bottom:2000px">
  <p>滚动我</p>
  <p>来回滚动我</p>
  <p>滚动我</p>
  <p>来回滚动我</p>
  <p>滚动我</p>
  <p>来回滚动我</p>
</div>

</body>
</html>

 根据特性实现表格的冻结列效果

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<style>
body{
margin:0px;
}
table{border-collapse: collapse;}
th,td{padding: 5px;text-align: center;border:2px solid #999;min- 100px;}
th{background-color: red;color:#fff;position: sticky;top:-1px;z-index: 2;}
th:first-child{z-index: 3;left:0px;}
th:nth-child(2){z-index: 3;left:110px;}
td:first-child{background-color: #333;color: #fff;position: sticky;left:0px; border:2px solid #999;}
td:nth-child(2){background-color: #333;color: #fff;position: sticky;left:111px;border:2px solid #999;}
</style>
<script src="https://cdn.staticfile.org/vue/2.5.17-beta.0/vue.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded",function(){
let t = new Vue({el:"#t"});
});
</script>
</head>

<body>
<table id="t">
<thead>
<tr>
<th v-for="(n,i) of 50">字段 {{i+1}}</th>
</tr>
</thead>
<tbody>
<tr v-for="(n,i) of 100">
<td v-for="(m,j) of 50">{{j+1}}</td>
</tr>
</tbody>
</table>
</body>

</html>

 

在一个小程序开发项目中;tabs组件使用了粘性定位,其中有tab栏的切换;tab栏底部是大段列表内容list-container内容的展示;其中展示内容有click事件(或者说是touch事件);ios以及pc浏览器中对点击的测试是正常的;但在安卓手机中!!!!我的天,点击穿透了!!并且,尝试去掉list-container中的item的点击跳转,发现tab切换的点击没有了反应,事件消失了!!!
设置断点,查看事件流的走向:首先事件捕获-->目标节点tab-->事件冒泡;这个泡居然冒到了container-list中的item。。。简直噩梦
大致的项目结构:

html结构

<div class="service-wrap">
 
<tab>这是tab切换</tab>
 
<div class="list-container">
 
<!--for循环有很多item-->
 
<item></item>
 
<item></item>
 
</div>
 
</div>
解决办法:
1.在使用组件库的tab时,外层套一个div,防止点击穿透和不正常的事件流走向
或者(一个治标不治本的方法,具体看业务场景)
2.组件库的样式无法改,sticky作为tab组件的行内样式,因为我使用这个tab时是直接在viewpoint的顶部的,这是完全可以用fixed达到效果。我在调用类的外部设置了position:fixed !import;样式最高优先级去覆盖了组件库中的定位样式,就正常了。
一点想法:
由于安卓系统对sticky粘性定位的惨淡支持;如果业务场景可以用其它定位解决,那就还是不要用sticky吧
原文地址:https://www.cnblogs.com/jscai/p/13680187.html