js中的浏览器滚动事件

实例: 仿写京东的滚动后出现上边栏
链接: 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>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值