javascript 滚动条

来源:互联网 发布:python高性能编程 pdf 编辑:程序博客网 时间:2024/04/29 10:49

滚动条的实现原理和上一篇文章中的拖拽有很大关系,滑动条就是通过拖拽实现的,通过计算滑动条的拖拽区间来得出一个比例scale,这个就是咱们要用到的文字滚动距离了,

div3里别忘记添加文字

具体代码如下

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>New Web Project</title><style>#parent{width:600px;height:20px;background:#CCCCCC;position: relative;}#div1{width: 20px;height:20px;top:0px;left:0px;background:#FF0000;position: absolute;}#div2{width:300px;height:300px;border:1px solid #222222;position:relative;margin-top:10px;overflow:hidden;}#div3{padding:5px;position: absolute;}</style><script>window.onload=function(){var oParent=document.getElementById('parent');var oDiv1=document.getElementById('div1');var oDiv2=document.getElementById('div2');var oDiv3=document.getElementById('div3');oDiv1.onmousedown=function(evt){var e=evt||event;var disX=e.clientX-oDiv1.offsetLeft;document.onmousemove=function(evt1){var e1=evt1||event;var posX=e1.clientX-disX;if(posX<0){posX=0;}else if(posX>oParent.offsetWidth-oDiv1.offsetWidth){posX=oParent.offsetWidth-oDiv1.offsetWidth;}oDiv1.style.left=posX+'px';var scale=posX/(oParent.offsetWidth-oDiv1.offsetWidth);oDiv3.style.top=-(oDiv3.offsetHeight-oDiv2.offsetHeight)*scale+'px';};document.onmouseup=function(){document.onmousemove=null;document.onmouseup=null;};return false;};};</script></head><body><div id="parent"><div id="div1"></div></div><div id="div2"><div id="div3"></div></div></body></html>
运行结果图:



0 0