scroll-behavior属性
当用户手动导航或者 CSSOM scrolling API 触发滚动操作时,CSS 属性 scroll-behavior 为一个滚动框指定滚动行为,当用户通过鼠标滑轮滚动或者手机触屏滚动,不受这个属性的影响。在根元素中指定这个属性时,它反而适用于视窗。
scroll-behavior属性包括: smooth | auto
;
auto
: 默认值,表示滚动框立即滚动到指定位置。 smooth
表示允许滚动时采用平滑过渡,而不知直接滚动到相应位置,最常见的比如回到顶部按钮和锚点。
scroll-behavior浏览器支持情况:
- 通过锚点的方式实现,代码如下:
html代码:
1 <div class="tab-box"> 2 <div class="tab-t"> 3 <a class="labels" href="#tab1">选项卡1</a> 4 <a class="labels" href="#tab2">选项卡2</a> 5 <a class="labels" href="#tab3">选项卡3</a> 6 </div> 7 <div class="tab-body"> 8 <div class="content" id="tab1"> 9 <p>我是选项卡1</p> 10 </div> 11 <div class="content" id="tab2"> 12 <p>我是选项卡2</p> 13 </div> 14 <div class="content" id="tab3"> 15 <p>我是选项卡3</p> 16 </div> 17 </div> 18 </div>
less代码:1 .tab-box{ 2 margin: 20px; 3 .labels { 4 width: 100px; 5 margin-right: -1px; 6 border: 1px solid #ccc; 7 border-bottom: 0; 8 padding-top: 5px; 9 padding-bottom: 5px; 10 background-color: #eee; 11 text-align: center; 12 display: inline-block; 13 text-decoration: none; 14 color:#555; 15 } 16 .tab-body { 17 height: 200px; 18 border: 1px solid #ccc; 19 scroll-behavior: smooth; 20 overflow: hidden; 21 .content { 22 height: 100%; 23 padding: 0 20px; 24 position: relative; 25 overflow: hidden; 26 input { 27 position: absolute; 28 top: 0; 29 height: 100%; 30 width: 100px; 31 border: 0; 32 padding: 0; 33 margin: 0; 34 clip: rect(0 0 0 0); 35 } 36 } 37 } 38 }
- 通过label和表单元素得到焦点的特性实现,代码如下:
html代码:
1 <div class="tab-box"> 2 <div class="tab-t"> 3 <label class="label" for="tab1">选项卡1</label> 4 <label class="label" for="tab2">选项卡2</label> 5 <label class="label" for="tab3">选项卡3</label> 6 </div> 7 <div class="tab-body"> 8 <div class="content"><input id="tab1" type="text"> 9 <p>我是选项卡1</p> 10 </div> 11 <div class="content"><input id="tab2" type="text"> 12 <p>我是选项卡2</p> 13 </div> 14 <div class="content"><input id="tab3" type="text"> 15 <p>我是选项卡3</p> 16 </div> 17 </div> 18 </div>
less代码:
1 .tab-box{ 2 margin: 20px; 3 .label { 4 width: 100px; 5 margin-right: -1px; 6 border: 1px solid #ccc; 7 border-bottom: 0; 8 padding-top: 5px; 9 padding-bottom: 5px; 10 background-color: #eee; 11 text-align: center; 12 display: inline-block; 13 } 14 .tab-body { 15 height: 200px; 16 border: 1px solid #ccc; 17 scroll-behavior: smooth; 18 overflow: hidden; 19 .content { 20 height: 100%; 21 padding: 0 20px; 22 position: relative; 23 overflow: hidden; 24 input { 25 position: absolute; 26 top: 0; 27 height: 100%; 28 width: 100px; 29 border: 0; 30 padding: 0; 31 margin: 0; 32 clip: rect(0 0 0 0); 33 } 34 } 35 } 36 }