按钮控制菜单上下滚动

        前两天学习了定时器,为了更好地理解,做了几个关于它的小练习。这个练习本来觉得很容易,但是花的调试时间最久,主要的问题就出在高度值的获取上,还有滚动对象的确定。我是利用top值的变化来实现滚动的功能,向上滚动top减小,向下滚动top值增加。获取页面当前的top值通过封装函数实现:


实现top值的变化是通过定时器,定时器所需函数主要是实现相同时间间隔内top变化固定的值:


需要注意的是z-index和overflow的正确运用

实现效果:


代码如下:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>按钮控制菜单的上下滚动</title>
	<style type="text/css">
	#contain{
		width: 300px;
		height: 500px;
		margin: 0 auto;
		position: relative;
		overflow: hidden;
	}	
	.head{
		width: 280px;
		height: 30px;
		line-height: 30px;
		padding:0 10px;
		background: blue;
		border-radius: 10px 10px 0 0;
		z-index: 10; 
	}
	#up,#down{
		width: 300px;
		height: 30px;
		background: #617786;
		text-align: center;
		line-height: 30px;
		position: absolute;
		cursor: pointer;
		z-index: 2;
	}
	#up{
		top: 30px;
		z-index: 10;
	}
	#down{
		top: 470px;
	}
	#content{		
		height: 410px;
		position: absolute;
		top: 60px;	
		z-index: -1;		
	}
	#content ul{
		margin: 0;
		padding: 0;
		list-style: none;
		overflow: hidden;
		z-index: -1;
		
	}
	#content ul li{
		width: 300px;
		height: 60px;
		background: #99a7ce;
		overflow: hidden;
		border-bottom: 1px solid #ccc;
		color: white;
		text-align: center;
		line-height: 60px;
		font-size: 20px;
	}
	</style>
</head>
<body>
<div id="contain">
	<div class="head">妙味课堂</div>
	<div id="up">向上滚动</div>
	<div id="content">
		<ul>
			<li>1</li>
			<li>2</li>
			<li>3</li>
			<li>4</li>
			<li>5</li>
			<li>6</li>
			<li>7</li>
			<li>8</li>
			<li>9</li>
			<li>10</li>
		</ul>
	</div>
	<div id="down">向下滚动</div>
</div>

<script type="text/javascript">
	var cont=document.getElementById('content');
	var up=document.getElementById('up');
	var down=document.getElementById('down');
	var oUl=cont.getElementsByTagName('ul');
	var timer1=null,timer2=null;

	up.οnmοusedοwn=function(){
		clearInterval(timer1);
		if(parseInt(getStyle(cont,'top'))>-140)
			timer1=setInterval(function(){	
				var dis=parseInt(getStyle(cont,'top'))-1;
				if(dis<=-140){
					clearInterval(timer1);
				}
				cont.style.top=dis+'px';
			},10);		
	}
	up.οnmοuseup=function(){
		clearInterval(timer1);
	}
	down.οnmοusedοwn=function(){
		clearInterval(timer1);
		clearInterval(timer2);
		if(parseInt(getStyle(cont,'top'))<60)		
			timer2=setInterval(function(){	
				var dis=parseInt(getStyle(cont,'top'))+1;
				if(dis>=60){
					clearInterval(timer2);
				}
				cont.style.top=dis+'px';
			},10);
	}
	down.οnmοuseup=function(){
		clearInterval(timer2);
	}
	function getStyle(obj ,attr){  
        return obj.currentStyle ? obj.currentStyle[attr] :getComputedStyle(obj ,false)[attr];  
    }  
</script>
</body>
</html>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值