实例: 仿写京东的滚动后出现上边栏
链接: demo
html结构
<body>
<div class="topic">
<div class="container">
</div>
</div>
<box id="box">
<div class="container">
<div class="top">
<div class="left"></div>
<div class="input">
<input type="text" value="无线鼠标" />
<button type="button"></button>
</div>
<div class="btn">
<img src="images/car.png" >
<p>我的购物车</p>
</div>
</div>
</div>
</box>
<fei>
<button id="fei" type="button">top</button>
</fei>
css代码
<style type="text/css">
.topic{
height: 55px;
}
box{
box-sizing: border-box;
height: 55px;
position: fixed;
top: 0;
transform: translateY(-70px);
transition: all 1s linear;
border-bottom: 2px solid #f10011;
}
html,body{
height: 4000px;
}
.container{
width: 1010px;
margin: 0 auto;
}
.top{
height: 53px;
display: flex;
align-items: center;
}
.left{
height: 53px;
width: 266px;
background: url(./images/logo_02.png) no-repeat;
background-size: auto 100%;
}
.input{
box-sizing: border-box;
height: 40px;
width: 585px;
border: #e1251b solid 3px;
display: flex;
}
.input>input{
width: 517px;
border: none;
outline: none;
font-size: 13px;
color: #989898;
height: 34px;
line-height: 34px;
background: url(images/photo.png) no-repeat 482px center;
background-size: auto 70%;
box-sizing: border-box;
padding: 0 20px;
}
.input>button{
width: 62px;
height: 34px;
border: none;
outline: none;
background: url(images/search.png) no-repeat center;
background-color: #e1251b;
background-size: auto 50%;
}
.btn{
margin-left: 19px;
width: 140px;
box-sizing: border-box;
border: 2px solid #ececec;
height: 38px;
display: flex;
align-items: center;
justify-content: space-evenly;
color: #e6473f;
font-size: 14px;
}
.btn>img{
height: 16px;
width: 18px;
}
fei{
position: fixed;
bottom: 150px;
right: 240px;
font-size: 25px;
}
</style>
js代码,
- onscroll方法触发当鼠标滚轮发生时的函数,定义的top属性则为获取的滚动的距离.当距离大于500的时候会弹出上边框,及所谓的位移效果.
- fei节点是点击后自动向上滚动,这里采用了计时器,每5毫秒向上滚动5px
<script type="text/javascript">
function tanchu(){
box.style.transform = "translateY(0)"
}
function shouhui(){
box.style.transform = "translateY(-70px)"
}
window.onscroll = function(){
var top = document.documentElement.scrollTop || document.body.scrollTop
console.log(top)
if(top>500){
tanchu()
}else{
shouhui()
}
}
fei.onclick = function(){
var res = setInterval(function(){
document.documentElement.scrollTop = -5
// top -= 5
if(document.documentElement.scrollTop == 0){
clearInterval(res)
}
},5)
}
</script>