效果GIF图:
第一步 ul 中的css设置 <ul id = "list"></ul>
#list { overflow-x: auto//设置x轴可滑动 list-style: none//去掉li上的小点 white-space:nowrap//元素不换行 width: auto(宽度) }
第二步 li中的css设置 <li class = "item">
.item { margin-left: 20px//每个li设置间距为20px display: inline-block//让所有的li在一行 注意这里不能用float:left 因为设置float后里超过一屏后会自动换行 }
先介绍一下上面的重要的css中的属性作用,大家也可以去w3scholl去参考学习。
这只是在x轴上的滑动 有一个相对的是overflow-y 只在y轴上滑动
width是我们最常用的属性,但是我常用的为lenght和% 忽略了auto这个属性 我们大可不惜自己去计算宽度,使用auto可以自适应宽度。
使用用flex-box布局
#list { displey:-webkit-flexdisplay: flex-webkit-flex-flow:row nowrap//设置排列方式为横向排列,并且超出元素不换行 flex-flow:row nowrapoverflow-x: autolist-style: none}
效果图:
css
.box {
background: #eee
padding: 10px 0
white-space: nowrap
/*文本不会换行,文本会在在同一行上继续*/
overflow-y: auto
/*可滑动*/
}
/*自定义滚动条的伪对象选择器, CSS 可以隐藏滚动条*/
.box::-webkit-scrollbar {
display: none
}
.box1 {
width: 49%
margin-left: 3%
height: 100px
background: #fff
display: inline-block
/*行内块元素*/
}
html:
<div class="box">
<div class="box1"></div>
<div class="box1"></div>
<div class="box1"></div>
<div class="box1"></div>
<div class="box1"></div>
</div>
<meta charset="utf-8">
例如:
需求:导航栏实现横向滑动,适应移动端,当滑动到最后时,图标隐藏
css实现滑动效果:
style样式:
.scrollContainer{overflow:auto}
.box{
display:box
display:-webkit-box//也可使用display:flex
height:"40px"
}
.box span{
display: block !important//这是重点!!
width:"60px",
height: "40px"
line-height: "40px"
text-align:center
}
<div class="scrollContainer">
<div class="box">
<span>HT</span>
<span>CTC</span>
<span>SLT</span>
<span>AET</span>
<span>LET</span>
</div>
</div>
js中实现滑动效果:
思路:
当(滑动的距离=总滑动宽度-可视宽度 || 滑动的距离>总滑动宽度-可视宽度)时,隐藏图标,相反显示
domElement.scrollLeft(滑动距离)
domElement.scrollWidth(总滑动宽度-可视宽度)
domElement.clientWidth(可视宽度)