javascript按钮控制上下滚动的实现代码

发布时间:2020-02-20编辑:脚本学堂
本文介绍下,javascript实现的一个可以点击按钮,能够控制上下滚动的代码,有需要的朋友,可以参考下。

1、页面内容部分
 

<style>
.rgt_carlist{height:124px;overflow:hidden;}
</style>
<div class="rgt_nor_box">
<div id="scro_top" class="scro_up">1111111111</div>
<ul id="all_items" class="rgt_carlist">
<li>1111111111</li>
<li>2222222222</li>
<li>1111111111</li>
<li>2222222222</li>
<li>1111111111</li>
<li>2222222222</li>
<li>1111111111</li>
<li>2222222222</li>
<li>1111111111</li>
<li>2222222222</li>
</ul>
<div id="scro_bottom" class="scro_down">222222</div>
</div>

2、js代码部分
 

复制代码 代码示例:
<script language="javascript">
/**
 * 点击按钮控制上下滚动
 * Edit www.jb200.com
 * 2013/5/8 星期三
*/
function addLoadEvent(func){
 var oldonload = window.onload;
 if(typeof window.onload!= 'function' ){
   window.onload = func;
 }
 else{
  window.onload = function(){
  oldonload();
  func();
  }
 }
}
 
vscroll = function sglVscroll(){
 if(!document.getElementById ||!document.getElementsByTagName ||!document.getElementById("all_items")||!document.getElementById("scro_top")||!document.getElementById("scro_bottom") ) return false;
 var i = 1;//每次滚动一个像素
 var obj= document.getElementById("all_items");
 obj.scrollTop = 0;
 var lists = obj.getElementsByTagName("li");//检查ul里面有多少个li
 var height = lists.length*25;
 var dist = height-125;//检查ul可以滚动的距离
 var up_btn = document.getElementById("scro_top");
 var down_btn = document.getElementById("scro_bottom");
 var timeid;
 //把下面的函数作为一个变量传给setinterval才不会出问题
 toward_up=function(){
  var count = obj.scrollTop;
  if(count>0){
   count -= i;
   obj.scrollTop = count;
  }
 }
 toward_down=function(){
 
  var count = obj.scrollTop;
  if(count<dist){
   count +=i;
   obj.scrollTop = count;
  }
 }
 
 //鼠标在向上按钮时的效果
 up_btn.onmousedown = function(){
  timeid=setInterval(toward_up,20);
  this.className = "scro_up2";
 }
 up_btn.onmouseup = function(){
  clearInterval(timeid);
  this.className = "scro_up";
 }
 //鼠标在向下按钮时的效果
 down_btn.onmousedown = function(){
  timeid=setInterval(toward_down,20);
  this.className = "scro_down2";
 }
 down_btn.onmouseup = function(){
  clearInterval(timeid);
  this.className = "scro_down";
 }
}
addLoadEvent(vscroll);
</script>